Why should UpdateView have the model / queryset / get_queryset parameter defined when using form_class and not CreateView?

Works like a charm:

MyCreateView(CreateView): template_name = "my_template_name" form_class = MyModelForm success_url = "/success/" 

But the following:

 MyUpdateView(UpdateView): template_name = "my_template_name" form_class = MyModelForm success_url = "/success/" 

I get this error:

 MyUpdateView is missing a queryset. Define MyUpdateView.model, MyUpdateView.queryset, or override MyUpdateView.get_queryset(). 

Why is UpdateView model , queryset or get_queryset so as not to cause an error, but CreateView not? Can't it automatically infer it from the model used in ModelForm?

+6
source share
2 answers

Currently (official release of django 1.5.1), UpdateView calls self.get_object() to provide an instance object for the form.

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

And for the self.get_object method one of the following properties is required: model , queryset or get_queryset

While CreateView does not call self.get_object() .

From 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) 
+7
source

You may have a problem with your urls.py file.

I think you wrote in it:

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

but you have to change UpdateView to MyUpdateView, for example: url(r'foldername/(?P[0-9]+)/$', views.MyUpdateView.as_view(), name='update'),

+2
source

Source: https://habr.com/ru/post/949306/


All Articles