6

奇迹般有效:

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中使用的模型自动派生它吗?

4

2 回答 2

8

目前(django 1.5.1 正式版)UpdateView正在调用self.get_object()能够向instanceForm 提供对象。

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)
于 2013-07-12T11:16:39.230 回答
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'),

于 2016-07-25T07:24:41.807 回答