为什么在使用form_class而不是CreateView时,UpdateView需要定义model / queryset / get_queryset?

时间:2013-07-12 10:58:59

标签: django django-class-based-views

像魅力一样:

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需要modelquerysetget_queryset定义为CreateView不会导致错误?它不应该能够从ModelForm中使用的Model中自动派生出来吗?

2 个答案:

答案 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方法需要声明此属性之一:modelquerysetget_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'),