如何解决Django:基于参数类的视图
| 我试图使用通用的CreateView类来处理从同一基类继承的一组模型的表单。class BaseContent(models.Model):
...
class XContent(BaseContent):
...
class YContent(BaseContent):
...
为了使事情保持干燥,我想定义一个CreateView类,该类将处理从BaseContent继承的所有类。
该视图的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
这样的类属性来保持生成的模型形式的动态。覆盖ѭ6似乎与创建对象无关。
我尝试覆盖get_queryset()
,但是此方法不接受request
参数,也无法访问来自url模式的self.model_name
。
长话短说,如何根据从URL传递的参数使CreateView使用动态表单?
谢谢。
解决方法
您可以在called11ѭ中设置
model
属性,具体取决于所调用的网址:
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
做类似的操作...
, 有这个问题一段时间了,但是找到了解决方案。您需要重写在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,**kwargs)
...
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。