Ian Ward

CKAN contributor/tech lead
Urwid author
PyRF contributor
Speedometer author

Contributing to Open Source
IASA E-Summit, 2014-05-16
Urwid Applications
Urwid Intro
Unfortunate Python
Django 1.1

Moving to Python 3
Article Tags


Ian Ward's email:
first name at this domain

wardi on OFTC, freenode and github

Locations of visitors to this page

Django Forms Quick Reference

Posted on 2009-07-21, last modified 2009-11-19.

Django's forms have fields like models, but you access them in a completely different way. I've found it hard to remember the correct way to access form field data properly, so this is a summary of the things I need to do with forms and how to do them. In particular these are useful in the form's __init__ method after calling super() to set up the form the way you want to.

UPDATE: There were a few mistakes in my earlier version of this post, now corrected.

get a BoundField object for fieldname, including the field and its data
aform.fields['fieldname'] or aform['fieldname'].field
get a FormField object for fieldname
get/set the initial value displayed or id selected for an unbound form, getting this value from a bound form will raise an AttributeError
get/set the text data for a field, when getting it raises a KeyError if the form is unbound or if no data was passed in for fieldname UPDATE: this MultiValueDict includes the form prefix in its keys, indicating that it is likely not intended as a public interface
get the text data for fieldname, similar to: aform.data.get('fieldname', None) but it is safer because you get a KeyError if the field doesn't exist
get/set the errors for a field as a list of strings, when getting it raises KeyError if fieldname has no errors
get the list of errors for fieldname, similar to: aform.errors.get('fieldname', []) but it is safer because you get a KeyError if the field doesn't exist
the result of calling fieldname's clean() method or calling the form's clean_fieldname() method. This dictionary doesn't exist if the form is unbound or invalid.
del aform.fields['fieldname']
remove a field from a form (suggested by Graham Ullrich)

And here are a couple Form field attributes I often need to modify:

get/set the a ChoiceField's options which is a list of (id, display_text) tuples
get/set the a ModelChoiceField's queryset object, but NOTE: .choices will override this

If you're updating your form field's widgets, this is useful too: (suggested by Graham Ullrich)

get/set the a field's widget, eg. aform.fields['date_transacted'].widget = widgets.AdminDateWidget()

If I missed anything else please let me know by sending an email to at ian at this domain.

Tags: Django