excess.org

Ian Ward

Consulting
Generic Consulting Inc.
Software
Urwid 2010-01-25 (0.9.9.1)
Speedometer 2008-05-29 (2.6)
Templayer 2009-03-08 (1.5.1)
mkzip.py 2003-09-15 (1.2)
File Tosser 2001 (0.1e-6)
Writing
Tags

Home

Ian Ward's email:
first name at this domain

IRC: wardi on OFTC

Facebook profile

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.

aform['fieldname']
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
aform.fields['fieldname'].initial
get/set the initial value displayed or id selected for an unbound form, getting this value from a bound form will raise an AttributeError
aform.data['fieldname']
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
aform['fieldname'].data
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
aform.errors['fieldname']
get/set the errors for a field as a list of strings, when getting it raises KeyError if fieldname has no errors
aform['fieldname'].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
aform.cleaned_data['fieldname']
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:

aform.fields['choice_fieldname'].choices
get/set the a ChoiceField's options which is a list of (id, display_text) tuples
aform.fields['modelchoice_fieldname'].queryset
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)

aform.fields['fieldname'].widget
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