Django:基于参数类的视图

oma*_*mat 7 django django-views django-class-based-views

我试图使用通用的CreateView类来处理从同一基类继承的一组模型的表单.

class BaseContent(models.Model):
    ...

class XContent(BaseContent):
    ...

class YContent(BaseContent):
    ...
Run Code Online (Sandbox Code Playgroud)

为了保持DRY,我想定义一个CreateView类,它将处理来自BaseContent的所有继承类.

该视图的url模式为:

url(r'^content/add/(?P<model_name>\w+)/$', ContentCreateView.as_view(), name='content_add')
Run Code Online (Sandbox Code Playgroud)

这样的事情应该有效:

class ContentCreateView(CreateView):
    template_name = 'content_form.html'

    def get_model(self, request):
        # 'content' is the name of the application; model_name is 'xcontent', 'ycontent', ...
        return ContentType.objects.get_by_natural_key('content', self.model_name)
Run Code Online (Sandbox Code Playgroud)

但是我得到了这个例外:

ContentCreateView is missing a queryset. Define ContentCreateView.model, ContentCreateView.queryset, or override ContentCreateView.get_object().
Run Code Online (Sandbox Code Playgroud)

这个建议似乎并不成立,因为我不愿意设置类属性,model或者queryset保持模型表单生成动态.覆盖get_object它似乎与创建对象无关.

我试过覆盖get_queryset()但是这个方法不接受request参数,也没有self.model_name来自url模式的访问权限.

长话短说,如何让CreateView使用基于从url传递的参数的动态表单?

谢谢.

Ber*_*ant 1

您可以根据调用的 url设置model您的属性:urls.py

url(r'^content/add/x/$', 
    ContentCreateView.as_view(model=XContent), name='x_content_add'),
url(r'^content/add/y/$', 
    ContentCreateView.as_view(model=YContent), name='y_content_add')
Run Code Online (Sandbox Code Playgroud)

我承认它并不完美,因为您有点重复自己,但因此您可以根据模型对同一视图使用不同的名称!除此之外,您还可以通过覆盖做类似的事情form_class...