How to add and use additional fields on Django model formsets

March 22, 2011

Suppose that you have a model formset and for some reason you want to add an additional field to each individual form (or perhaps you want to reinterpret a model field into something that is more user-friendly), a field that is of course not in your model schema.

At one level, adding custom fields or custom field handling to a model formset is relatively simple once you know what to do. At another level, the question is how to get access to information about the field. The normal way of dealing with a model formset is:

if formset.is_valid():
  instances = formset.save(commit=False)
  for thing in instances:
    ....

The problem is that thing is a model instance, not a form, and our new field appears only in the form; since it is not in the model schema, Django cannot copy it to the model instance it derives from the form information. When you're using a model form or model formset, the only thing that Django does with fields that are not in the model is validate them and then (effectively) throw them away.

(This can sometimes be useful, for example an 'I agree to these terms' checkbox. If you make this a boolean field and require it, the field and thus the form will not validate until it is ticked.)

If we want access to non-model fields in a model formset, we need to directly iterate the forms of the formset instead of just iterating the model instances. These are available through formset.forms but this has all of the forms in the formset, including ones that haven't been modified or used; we need to exclude them. The way to do this is:

if formset.is_valid():
  for form in formset.forms:
    if not form.has_changed():
      continue
    thing = form.save(commit=False)
    ... process ...

You now have direct access to both the form itself and the corresponding model instance, so you can check the form for your extra fields and do whatever processing you need.

Note that you do not have to specifically check that the form itself is valid. Because the entire formset validated, we know that any changed form is itself valid. Unchanged forms may well not be if this was a formset for entering new data, since they will still be blank.

(This applies to Django 1.2.5, and my disclaimer is that I am new to Django so this may well not be considered the Django-correct way to do this particular thing.)

PS: as far as I can see, you do not want to use formset.cleaned_data here. Although it exists, it's the basic form data with no clear way to turn it into a model instance and it still includes all of the unchanged or blank forms in the formset.

Sidebar: the actual problem in concrete

What I've written here sounds very abstract and you might be wondering why anyone would want to do something like this, so lets make it concrete with my Django application, our account request management system.

Account requests normally have to be approved by their sponsor; however, staff can approve requests on behalf of the sponsor. Staff can also enter a bunch of new account requests, which are normally not pre-approved and need the sponsor's approval. Suppose that we want to add a checkbox to the form to say 'mark this request as approved when it gets created', to save staff from the annoyance of creating a bunch of new requests and then immediately going off to approve them all.

This checkbox is not a model schema field directly (although ticking it results in a different value for schema field). I suppose that with a lot of effort we could create some sort of custom widget mapping that turns the 'status of request' model schema field (normally a three way choice) into a boolean tickbox (unticked makes the status 'Pending', ticked makes it 'Approved'), but I rather think that my approach here is simpler.


Written on 22 March 2011.
« Some notes on doing things with Django model formsets
XHTML and web authoring folklore »

These are my WanderingThoughts
(About the blog)

Full index of entries
Recent comments

This is part of CSpace, and is written by ChrisSiebenmann.
Twitter: @thatcks

* * *

Categories: links, linux, programming, python, snark, solaris, spam, sysadmin, tech, unix, web

This is a DWiki.
GettingAround
(Help)

Search:

Page tools: View Source, Add Comment.
Search:
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Tue Mar 22 13:39:17 2011
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.