A year ago I wrote a custom CheckboxSelectMultiple control for django. My application needed to display a series of checkboxes on the webpage, but the default django control did not allow iteration over each checkbox when the control was rendered in the template (as it was possible with the RadioSelect control). This finer control was necessary because I needed to insert extra HTML between each checkbox.

As of version 0.95, django has been under heavy changes, and my custom control no longer works. In particular, the old forms module is being discarded in favor of the newforms module that will become the default forms module sometime in the future. A good explanation can be found in the on-site django documentation, under newforms-migration plan.

The good news is that newforms allows access to individual items of the form fields, multiple-select fields included. The newforms documentation is still work in progress, so it took me a while to figure out how to do it… by inspecting the source code and regression tests. It seems pretty obvious now, should have asked in the django-users list.

The example code has been tested with django svn release 4812 (2007-3-23).

2007-03-27: By mistake I published an incorrect version of views.py. Code has been corrected so that now add_post saves the tag field as expected. (Post has a many-to-many relationship with Tag, so form.save() is not enough to save the form data.)

2007-04-12: The code for views.py has been corrected again. The code posted 2007-03-27 works, but as I discovered later, there is no need to create another object (p = Post(**cleandata)) to handle the many-to-many field data. form.save() takes care of everything, as expected.

2007-04-24: You may be interested in this post.

template

models.py

views.py

views.py

This is an old version of views.py. The code works, but as I discovered later, there is no need to create another object (p = Post(**cleandata)) to handle the many-to-many field data. form.save() takes care of everything, as expected.