I'd like to use the class based generic views of django 1.3 for forms, but sometimes have to manage multiple form classes in one form. However, it looks like the existing views based on FormMixin assume a single form class.
Is this possible with generic views and how would I do it?
EDIT: to clarify, I have one form but more than one (ModelForm based) class. For example in the inline_formset example in the django docs, I would want to present a page where an author and his books can be edited at once, in a single form:
author_form = AuthorForm(request.POST, instance = author)
books_formset = BookInlineFormSet(request.POST, request.FILES, instance=author)
Facing similar problem, I've come to conclusion that it's not possible.
Though having multiple forms per page itself turned out to be a design mistake, presenting all sorts of troubles. E.g., user fills two forms, clicks submit on one of them and loses data from the other. Workaround requires complicated controller that needs to be aware of the state of all forms on the page. (See also here for some discussion on related problem.)
If having multiple forms per page isn't your exact requirement, I'd suggest to look at alternative solutions.
For example, it's usually possible to show user only one editable form at a time.
In my case, I switched to django-formwizard
(not a django.contrib one, which is a bit old and seems to be currently under a redesign, but this one Update: Beginning with release 1.4 of Django, django-formwizard
app will be available in django.contrib
, replacing old formwizard. It's already in trunk, see docs). For the user I made it to look like there are actually multiple forms on the page, but only one is editable. And user had to fill forms in predetermined order. This made dealing with multiple forms much easier.
Otherwise, if forms really need to be presented all at once, it may make sense to combine them into one.
UPDATE (after your clarification):
No, you can't deal with formsets using generic FormView
either. Though your example appears to be quite simple to implement: I think it's very similar to this example in Django docs on formsets. It deals with two formsets, and you just need to replace one with the form (I think you still need to specify prefix to avoid possible clashes of elements' id
attributes).
In short, in your case I'd subclass django.views.generic.base.View
and override get()
and post()
methods to deal with form and formset similar to above example from Django docs.
In this case, I think it's fine to present both form and formset editable—with a single button to submit them both.
ANOTHER UPDATE:
There's an active recent ticket in Django trac, #16256
More class based views: formsets derived generic views. If all goes well, new generic views will be added to Django: FormSetsView
, ModelFormSetsView
and InlineFormSetsView
. Particularly, the last one ‘provides a way to show and handle a model with it's inline formsets’.