7

Like much documentation on generic views in Django, I can't find docs that explicitly describe how to use the new Class-Based Generic Views with Django Forms.

How is it done?

Duncan Parkes
  • 1,902
  • 1
  • 15
  • 24

2 Answers2

3

What have you tried so far? The class based views are pretty new, and the docs don't have a lot of examples, so I think you're going to need to get your hands dirty and experiment!

If you want to update an existing object, then try using UpdateView. Look at the mixins it uses (e.g ModelFormMixin, SingleObjectMixin, FormMixin) to see which methods you can/have to override.

Good luck!

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • UpdateView looks to be what I need. If I understand the docs you linke dot correctly, I don't even need to write a separate subclass for my form(s). My problem is that I am fairly new to Django, so some actual working examples would really help me. thanks for the links though. –  Jul 14 '11 at 10:23
2

The easiest way to use model forms with class based views is to pass in the model and keep a slug / pk captured in 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 obtain more complex logic. You can also pass a queryset instead of a model object.

Another way is to create a modelform in forms.py and then pass form_class to the 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.

acid_crucifix
  • 362
  • 2
  • 12
  • How would one use a generic version of create to add an "entry" to class "category"? class Category(models.Model): title = models.CharField) slug = models.CharField() entry = models.ManyToManyField(Entry) – Bryce Jun 12 '12 at 04:59
  • url(r'^myurl/$', CreateView.as_view(model=Category, template_name="template.html")) – acid_crucifix Jul 15 '12 at 15:02