Generic views based on the Django class and ModelForms

Like a lot of documentation on general views in Django, I cannot find documents that explicitly describe how to use the new general views based on classes with Django formats.

How to do it?

+7
source share
2 answers

What have you tried? Class-based views are fairly new, and there aren't a lot of examples in the docs, so I think you will need to get your hands dirty and experiment!

If you want to update an existing object, try using UpdateView . Look at the SingleObjectMixin he uses (e.g. ModelFormMixin , SingleObjectMixin , FormMixin ) to find out which methods you can / should override.

Good luck

+4
source

The easiest way to use model forms with class-based views is to pass in the model and save the slug / pk written in the url, in which case you will not need to write any view code.

 url(r'^myurl/$', CreateView.as_view(model=mymodel)) #Creates a model form for model mymodel url(r'^myurl/(?<pk>\w+)/$', UpdateView.as_view(model=mymodel)) #Creates a model form for model mymodel and updates the object having pk as specified in url url(r'^myurl/(?<slug>\w+)/$', DeleteView.as_view(model=mymodel, slug_field="myfield")) #Creates a model form for model mymodel and deletes the object denoted by mymodel.objects.get(my_field=slug) 

You can also override methods to get more complex logic. You can also pass a set of queries instead of a model object.

Another way is to create modelform in forms.py and then pass form_class to url as

 url(r'^myurl/$', CreateView.as_view(form_class=myform)) 

This method allows you to define form functions as well as meta attributes for the form.

+2
source

All Articles