2013-07-12 84 views
6

就像一個魅力:爲什麼UpdateView需要在使用form_class而不是CreateView時定義model/queryset/get_queryset?

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

回答

7

目前(django 1.5.1正式發佈)UpdateView正在調用self.get_object()能夠提供instance對象到Form中。

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) 
2

你可能在你的urls.py文件有問題。

我想你在上面寫的是:

url(r'foldername/(?P[0-9]+)/$', views.UpdateView.as_view(), name='update'),

但你必須更新視圖改變爲MyUpdateView,像這樣: url(r'foldername/(?P[0-9]+)/$', views.MyUpdateView.as_view(), name='update'),

相關問題