像魅力一样:
MyCreateView(CreateView):
template_name = "my_template_name"
form_class = MyModelForm
success_url = "/success/"
但以下情况并非如此:
MyUpdateView(UpdateView):
template_name = "my_template_name"
form_class = MyModelForm
success_url = "/success/"
我收到此错误:
MyUpdateView is missing a queryset. Define MyUpdateView.model, MyUpdateView.queryset, or override MyUpdateView.get_queryset().
为什么UpdateView
需要model
,queryset
或get_queryset
定义为CreateView
不会导致错误?它不应该能够从ModelForm中使用的Model中自动派生出来吗?
答案 0 :(得分:8)
目前(django 1.5.1正式发布)UpdateView
正在调用self.get_object()
以便能够向表单提供instance
个对象。
来自https://github.com/django/django/blob/1.5c2/django/views/generic/edit.py#L217:
def get(self, request, *args, **kwargs):
self.object = self.get_object()
return super(BaseUpdateView, self).get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
self.object = self.get_object()
return super(BaseUpdateView, self).post(request, *args, **kwargs)
并且self.get_object
方法需要声明此属性之一:model
,queryset
或get_queryset
CreateView
不要拨打self.get_object()
。
来自https://github.com/django/django/blob/1.5c2/django/views/generic/edit.py#L194:
def get(self, request, *args, **kwargs):
self.object = None
return super(BaseCreateView, self).get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
self.object = None
return super(BaseCreateView, self).post(request, *args, **kwargs)
答案 1 :(得分:2)
您的urls.py文件可能有问题。
我认为你写的是:
url(r'foldername/(?P[0-9]+)/$', views.UpdateView.as_view(), name='update'),
但您必须将UpdateView更改为MyUpdateView,如下所示:
url(r'foldername/(?P[0-9]+)/$', views.MyUpdateView.as_view(), name='update'),