Multi-Object-Edit With Django FormSets
I had to write a multi-object edit table the other day for a Django project and as such I dove into the FormSet Documentation. Django's documentation is really good usually but the part abut the FormSets was a bit of a letdown.
So in case anybody else is in the same situation here is some code of how I did it (written from memory - should still be okay I hope).
# forms.py
# creating a FormSet for a specific Model is easy
=
# now we want to add a checkbox so we can do stuff to only selected items
# this is where you can add additional fields to a ModelFormSet
# this is also where you can change stuff about the auto generated form
=
.. =
After writing the FormSet itself here is the view:
# views.py
# we have multiple actions - save and delete in this case
=
=
# iterate over all forms in the formset
# only do stuff for forms in which is_checked is checked
# we need to call save to get an actual model but
# there is no need to hit the database hence the
# commit=False
=
# now that we got a model we can delete it
=
return
Now all that's missing is the template:
is_checked
somefield
someotherfield
{% for form in formset.forms %}
{# don't forget about the id field #}
{{ form.id }}
{{ form.is_checked }}
{{ form.somefield }}
{{ form.someotherfield }}
{% endfor %}
{# and don't forget about the management form #}
{{ formset.management_form }}
{% csrf_token %}
save
delete
Of course there is stuff still missing – you won't see errors in your form for example. But you get the general idea.
Edit 31.10.2012:
Thanks to Trinh Nguyen for bringing my attention to some stupid errors in the code and the inspiration to do some more commenting.