我正在尝试使用泛型CreateView类来处理从同一基类继承的一组模型的表单。
class BaseContent(models.Model):
...
class XContent(BaseContent):
...
class YContent(BaseContent):
...
为了保持简单,我想定义一个处理所有从BaseContent继承的类的CreateView类。
该查看器url模式为:
url(r'^content/add/(?P<model_name>\w+)/$', ContentCreateView.as_view(), name='content_add')
像这样的东西应该是有效的:
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)
但是我得到了一个例外:
ContentCreateView is missing a queryset. Define ContentCreateView.model, ContentCreateView.queryset, or override ContentCreateView.get_object().
这个建议似乎行不通,因为我不愿意设置像model
或queryset
这样的类属性来保持生成的模型表单的动态性。覆盖get_object
似乎与创建对象无关。
我尝试覆盖get_queryset()
,但此方法不接受request
参数,也无法访问来自url模式的self.model_name
。
长话短说,如何让CreateView使用基于从url传递的参数的动态表单?
谢谢。
发布于 2011-06-27 19:34:02
您可以从您的urls.py
设置model
属性,具体取决于所调用的url:
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')
我承认这并不完美,因为你在重复自己,但因此你有一个优势,即相同的视图有不同的名称,这取决于模型!除此之外,你也可以用覆盖form_class
来做一些类似的事情。
发布于 2015-12-10 13:35:55
这个问题已经有一段时间了,但找到了解决方案。您需要覆盖在as_view() (django.views.generic.base)中定义的调度方法,如下所示:
class ContentCreateView(CreateView):
def dispatch(self, request, *args, **kwargs):
for app in ['foo', 'bar']:
model = models.get_model(app, kwargs['modelname'])
if model:
self.model = model
break
return super(GenericEdit, self).dispatch(request, *args, **kwargs)
...
...
https://stackoverflow.com/questions/6478383
复制