Forms. Django Software
Django software is a free and open-source web framework written in Python. It is designed to make the development of complex, database-driven websites quick and easy. Django emphasizes reusability and pluggability of components, rapid development, and clean, pragmatic design. It is maintained by an active community of developers worldwide.
Advertisement
Advertisement
Django Documentation, Release 1.5.12
modified_time
( name)
Returns a datetime object containing the last modified time. For storage systems that aren’t able to return the last modified time, this will raise NotImplementedError instead.
open
( name , mode=’rb’)
Opens the file given by name. Note that although the returned file is guaranteed to be a File object, it might actually be some subclass. In the case of remote file storage this means that reading/writing could be quite slow, so be warned.
path
( name)
The local filesystem path where the file can be opened using Python’s standard open(). For storage systems that aren’t accessible from the local filesystem, this will raise NotImplementedError instead.
save
( name , content)
Saves a new file using the storage system, preferably with the name specified. If there already exists a file with this name name, the storage system may modify the filename as necessary to get a unique name. The actual name of the stored file will be returned.
The content argument must be an instance of
or of a subclass of
size
( name)
Returns the total size, in bytes, of the file referenced by name. For storage systems that aren’t able to return the file size this will raise NotImplementedError instead.
url
( name)
Returns the URL where the contents of the file referenced by name can be accessed. For storage systems that don’t support access by URL this will raise NotImplementedError instead.
Forms
Detailed form API reference. For introductory material, see
The Forms API
About this document
This document covers the gritty details of Django’s forms API. You should read the
introduction to working with forms
first.
Bound and unbound forms
A
instance is either bound to a set of data, or unbound.
• If it’s bound to a set of data, it’s capable of validating that data and rendering the form as HTML with the data displayed in the HTML.
• If it’s unbound, it cannot do validation (because there’s no data to validate!), but it can still render the blank form as HTML.
class Form
To create an unbound
instance, simply instantiate the class:
6.9. Forms 857
Django Documentation, Release 1.5.12
>>> f = ContactForm()
To bind data to a form, pass the data as a dictionary as the first parameter to your
class constructor:
>>> data = { 'subject' : 'hello' ,
...
...
...
'message'
'sender' :
:
'cc_myself'
'Hi there'
: True}
>>> f = ContactForm(data)
,
In this dictionary, the keys are the field names, which correspond to the attributes in your
class. The values are the data you’re trying to validate. These will usually be strings, but there’s no requirement that they be strings; the type of data you pass depends on the
Form.is_bound
If you need to distinguish between bound and unbound form instances at runtime, check the value of the form’s
attribute:
>>> f = ContactForm()
>>> f.is_bound
False
>>> f = ContactForm({ 'subject' : 'hello' })
>>> f.is_bound
True
Note that passing an empty dictionary creates a bound form with empty data:
>>> f = ContactForm({})
>>> f.is_bound
True
If you have a bound
instance and want to change the data somehow, or if you want to bind an unbound
instance to some data, create another
instance. There is no way to change data in a
instance. Once a
instance has been created, you should consider its data immutable, whether it has data or not.
Using forms to validate data
Form.is_valid()
The primary task of a
object is to validate data. With a bound
instance, call the
method to run validation and return a boolean designating whether the data was valid:
>>> data = { 'subject' : 'hello' ,
...
...
'message'
'sender' :
: 'Hi there' ,
...
'cc_myself' : True}
>>> f = ContactForm(data)
>>> f.is_valid()
True
Let’s try with some invalid data. In this case, subject is blank (an error, because all fields are required by default) and sender is not a valid email address:
>>> data = { 'subject' : '' ,
...
'message' : 'Hi there' ,
...
'sender' : 'invalid email address' ,
858 Chapter 6. API Reference
Django Documentation, Release 1.5.12
...
'cc_myself' : True}
>>> f = ContactForm(data)
>>> f.is_valid()
False
Form.errors
Access the
attribute to get a dictionary of error messages:
>>> f.errors
{'sender': [u'Enter a valid email address.'], 'subject': [u'This field is required.']}
In this dictionary, the keys are the field names, and the values are lists of Unicode strings representing the error messages. The error messages are stored in lists because a field can have multiple error messages.
You can access
without having to call
first. The form’s data will be validated the first time either you call
or access
The validation routines will only get called once, regardless of how many times you access
or call
Behavior of unbound forms
It’s meaningless to validate a form with no data, but, for the record, here’s what happens with unbound forms:
>>> f = ContactForm()
>>> f.is_valid()
False
>>> f.errors
{}
Dynamic initial values
Form.initial
Use
to declare the initial value of form fields at runtime. For example, you might want to fill in a username field with the username of the current session.
To accomplish this, use the
argument to a
. This argument, if given, should be a dictionary mapping
field names to initial values. Only include the fields for which you’re specifying an initial value; it’s not necessary to include every field in your form. For example:
>>> f = ContactForm(initial={ 'subject' : 'Hi there!' })
These values are only displayed for unbound forms, and they’re not used as fallback values if a particular value isn’t provided.
Note that if a
defines
and you include initial when instantiating the Form, then the latter initial will have precedence. In this example, initial is provided both at the field level and at the form instance level, and the latter gets precedence:
>>>
class CommentForm
(forms.Form):
...
...
name = forms.CharField(initial= url = forms.URLField()
'class' )
...
comment = forms.CharField()
>>> f = CommentForm(initial={ 'name' : 'instance' }, auto_id=False)
6.9. Forms 859
Django Documentation, Release 1.5.12
>>> print (f)
<tr><th>Name:</th><td><input type="text" name="name" value="instance" /></td></tr>
<tr><th>Url:</th><td><input type="text" name="url" /></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
Accessing “clean” data
Form.cleaned_data
Each field in a
class is responsible not only for validating data, but also for “cleaning” it – normalizing it to a consistent format. This is a nice feature, because it allows data for a particular field to be input in a variety of ways, always resulting in consistent output.
For example,
normalizes input into a Python datetime.date object. Regardless of whether you pass it a string in the format '1994-07-15', a datetime.date object, or a number of other formats, DateField will always normalize it to a datetime.date object as long as it’s valid.
Once you’ve created a
instance with a set of data and validated it, you can access the clean data via its cleaned_data attribute:
>>> data = { 'subject' : 'hello' ,
...
...
'message'
'sender' :
: 'Hi there' ,
...
'cc_myself' : True}
>>> f = ContactForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data
{'cc_myself': True, 'message': u'Hi there', 'sender': u'[email protected]', 'subject': u
˓→
'hello'}
Note that any text-based field – such as CharField or EmailField – always cleans the input into a Unicode string. We’ll cover the encoding implications later in this document.
If your data does not validate, the cleaned_data dictionary contains only the valid fields:
>>> data = { 'subject' : '' ,
...
'message' : 'Hi there' ,
...
...
'sender' : 'invalid email address'
'cc_myself' : True}
,
>>> f = ContactForm(data)
>>> f.is_valid()
False
>>> f.cleaned_data
{'cc_myself': True, 'message': u'Hi there'}
Until Django 1.5, the cleaned_data attribute wasn’t defined at all when the Form didn’t validate.
cleaned_data will always only contain a key for fields defined in the Form, even if you pass extra data when you define the Form. In this example, we pass a bunch of extra fields to the ContactForm constructor, but cleaned_data contains only the form’s fields:
>>> data = { 'subject' : 'hello' ,
...
...
'message'
'sender' :
: 'Hi there' ,
...
...
'cc_myself' : True,
'extra_field_1' : 'foo' ,
860 Chapter 6. API Reference
Django Documentation, Release 1.5.12
...
'extra_field_2' : 'bar' ,
...
'extra_field_3' : 'baz' }
>>> f = ContactForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data # Doesn't contain extra_field_1, etc.
{'cc_myself': True, 'message': u'Hi there', 'sender': u'[email protected]', 'subject': u
˓→
'hello'}
When the Form is valid, cleaned_data will include a key and value for all its fields, even if the data didn’t include a value for some optional fields. In this example, the data dictionary doesn’t include a value for the nick_name field, but cleaned_data includes it, with an empty value:
>>>
class OptionalPersonForm
(Form):
...
first_name = CharField()
...
...
last_name = CharField() nick_name = CharField(required=False)
>>> data = { 'first_name' : u'John' , 'last_name' : u'Lennon' }
>>> f = OptionalPersonForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data
{'nick_name': u'', 'first_name': u'John', 'last_name': u'Lennon'}
In this above example, the cleaned_data value for nick_name is set to an empty string, because nick_name is
CharField
, and CharFields treat empty values as an empty string. Each field type knows what its “blank” value is – e.g., for DateField, it’s None instead of the empty string. For full details on each field’s behavior in this case, see the “Empty value” note for each field in the “Built-in Field classes” section below.
You can write code to perform validation for particular form fields (based on their name) or for the form as a whole
(considering combinations of various fields). More information about this is in
Outputting forms as HTML
The second task of a Form object is to render itself as HTML. To do so, simply print it:
>>> f = ContactForm()
>>> print (f)
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type=
˓→
"text" name="subject" maxlength="100" /></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name=
˓→
"message" id="id_message" /></td></tr>
<tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender
˓→
" id="id_sender" /></td></tr>
<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox"
˓→ name="cc_myself" id="id_cc_myself" /></td></tr>
If the form is bound to data, the HTML output will include that data appropriately. For example, if a field is represented by an <input type="text">, the data will be in the value attribute. If a field is represented by an <input type="checkbox">
, then that HTML will include checked="checked" if appropriate:
>>> data = { 'subject' : 'hello' ,
...
'message' : 'Hi there' ,
...
...
'sender' : '[email protected]'
'cc_myself' : True}
>>> f = ContactForm(data)
,
6.9. Forms 861
Django Documentation, Release 1.5.12
>>> print (f)
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type=
˓→
"text" name="subject" maxlength="100" value="hello" /></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name=
˓→
"message" id="id_message" value="Hi there" /></td></tr>
<tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender
˓→
" id="id_sender" value="[email protected]" /></td></tr>
<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox"
˓→ name="cc_myself" id="id_cc_myself" checked="checked" /></td></tr>
This default output is a two-column HTML table, with a <tr> for each field. Notice the following:
• For flexibility, the output does not include the <table> and </table> tags, nor does it include the <form> and </form> tags or an <input type="submit"> tag. It’s your job to do that.
• Each field type has a default HTML representation. CharField and EmailField are represented by an
<input type="text"> . BooleanField is represented by an <input type="checkbox">. Note these are merely sensible defaults; you can specify which HTML to use for a given field by using widgets, which we’ll explain shortly.
• The HTML name for each tag is taken directly from its attribute name in the ContactForm class.
• The text label for each field – e.g. 'Subject:', 'Message:' and 'Cc myself:' is generated from the field name by converting all underscores to spaces and upper-casing the first letter. Again, note these are merely sensible defaults; you can also specify labels manually.
• Each text label is surrounded in an HTML <label> tag, which points to the appropriate form field via its id.
Its id, in turn, is generated by prepending 'id_' to the field name. The id attributes and <label> tags are included in the output by default, to follow best practices, but you can change that behavior.
Although <table> output is the default output style when you print a form, other output styles are available. Each style is available as a method on a form object, and each rendering method returns a Unicode object.
as_p()
Form.as_p() as_p() renders the form as a series of <p> tags, with each <p> containing one field:
>>> f = ContactForm()
>>> f.as_p() u'<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text"
˓→ name="subject" maxlength="100" /></p>\n<p><label for="id_message">Message:</
˓→ label> <input type="text" name="message" id="id_message" /></p>\n<p><label for=
˓→
"id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></
˓→ p>\n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name=
˓→
"cc_myself" id="id_cc_myself" /></p>'
>>> print (f.as_p())
<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text"
˓→ name="subject" maxlength="100" /></p>
<p><label for="id_message">Message:</label> <input type="text" name="message" id=
˓→
"id_message" /></p>
<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_
˓→ sender" /></p>
<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_
˓→ myself" id="id_cc_myself" /></p>
862 Chapter 6. API Reference
Django Documentation, Release 1.5.12
as_ul()
Form.as_ul() as_ul() renders the form as a series of <li> tags, with each <li> containing one field. It does not include the <ul> or </ul>, so that you can specify any HTML attributes on the <ul> for flexibility:
>>> f = ContactForm()
>>> f.as_ul() u'<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text"
˓→ name="subject" maxlength="100" /></li>\n<li><label for="id_message">Message:</
˓→ label> <input type="text" name="message" id="id_message" /></li>\n<li><label
˓→ for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender"
˓→
/></li>\n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox
˓→
" name="cc_myself" id="id_cc_myself" /></li>'
>>> print (f.as_ul())
<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text"
˓→ name="subject" maxlength="100" /></li>
<li><label for="id_message">Message:</label> <input type="text" name="message" id=
˓→
"id_message" /></li>
<li><label for="id_sender">Sender:</label> <input type="text" name="sender" id=
˓→
"id_sender" /></li>
<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_
˓→ myself" id="id_cc_myself" /></li>
as_table()
Form.as_table()
Finally, as_table() outputs the form as an HTML <table>. This is exactly the same as print. In fact, when you print a form object, it calls its as_table() method behind the scenes:
>>> f = ContactForm()
>>> f.as_table() u'<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject"
˓→ type="text" name="subject" maxlength="100" /></td></tr>\n<tr><th><label for="id_
˓→ message">Message:</label></th><td><input type="text" name="message" id="id_
˓→ message" /></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td>
˓→
<input type="text" name="sender" id="id_sender" /></td></tr>\n<tr><th><label
˓→ for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_
˓→ myself" id="id_cc_myself" /></td></tr>'
>>> print (f.as_table())
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject"
˓→ type="text" name="subject" maxlength="100" /></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name=
˓→
"message" id="id_message" /></td></tr>
<tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name=
˓→
"sender" id="id_sender" /></td></tr>
<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox
˓→
" name="cc_myself" id="id_cc_myself" /></td></tr>
Styling required or erroneous form rows
Form.error_css_class
Form.required_css_class
6.9. Forms 863
Django Documentation, Release 1.5.12
It’s pretty common to style form rows and fields that are required or have errors. For example, you might want to present required form rows in bold and highlight errors in red.
The
class has a couple of hooks you can use to add class attributes to required rows or to rows with errors: simply set the
and/or
attributes:
class ContactForm
(Form): error_css_class = 'error' required_css_class = 'required'
# ... and the rest of your fields here
Once you’ve done that, rows will be given "error" and/or "required" classes, as needed. The HTML will look something like:
>>> f = ContactForm(data)
>>> print (f.as_table())
<tr class="required"><th><label for="id_subject">Subject:</label>
<tr class="required"><th><label for="id_message">Message:</label>
<tr class="required error"><th><label for="id_sender">Sender:</label>
<tr><th><label for="id_cc_myself">Cc myself:<label> ...
...
...
...
Configuring HTML <label> tags
An HTML <label> tag designates which label text is associated with which form element. This small enhancement makes forms more usable and more accessible to assistive devices. It’s always a good idea to use <label> tags.
By default, the form rendering methods include HTML id attributes on the form elements and corresponding
<label> tags around the labels. The id attribute values are generated by prepending id_ to the form field names.
This behavior is configurable, though, if you want to change the id convention or remove HTML id attributes and
<label> tags entirely.
Use the auto_id argument to the Form constructor to control the label and id behavior. This argument must be
True , False or a string.
If auto_id is False, then the form output will not include <label> tags nor id attributes:
>>> f = ContactForm(auto_id=False)
>>> print (f.as_table())
<tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /></td></
˓→ tr>
<tr><th>Message:</th><td><input type="text" name="message" /></td></tr>
<tr><th>Sender:</th><td><input type="text" name="sender" /></td></tr>
<tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr>
>>> print (f.as_ul())
<li>Subject: <input type="text" name="subject" maxlength="100" /></li>
<li>Message: <input type="text" name="message" /></li>
<li>Sender: <input type="text" name="sender" /></li>
<li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
>>> print (f.as_p())
<p>Subject: <input type="text" name="subject" maxlength="100" /></p>
<p>Message: <input type="text" name="message" /></p>
<p>Sender: <input type="text" name="sender" /></p>
<p>Cc myself: <input type="checkbox" name="cc_myself" /></p>
If auto_id is set to True, then the form output will include <label> tags and will simply use the field name as its id for each form field:
864 Chapter 6. API Reference
Django Documentation, Release 1.5.12
>>> f = ContactForm(auto_id=True)
>>> print (f.as_table())
<tr><th><label for="subject">Subject:</label></th><td><input id="subject" type="text"
˓→ name="subject" maxlength="100" /></td></tr>
<tr><th><label for="message">Message:</label></th><td><input type="text" name="message
˓→
" id="message" /></td></tr>
<tr><th><label for="sender">Sender:</label></th><td><input type="text" name="sender"
˓→ id="sender" /></td></tr>
<tr><th><label for="cc_myself">Cc myself:</label></th><td><input type="checkbox" name=
˓→
"cc_myself" id="cc_myself" /></td></tr>
>>> print (f.as_ul())
<li><label for="subject">Subject:</label> <input id="subject" type="text" name=
˓→
"subject" maxlength="100" /></li>
<li><label for="message">Message:</label> <input type="text" name="message" id=
˓→
"message" /></li>
<li><label for="sender">Sender:</label> <input type="text" name="sender" id="sender" /
˓→
></li>
<li><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself"
˓→ id="cc_myself" /></li>
>>> print (f.as_p())
<p><label for="subject">Subject:</label> <input id="subject" type="text" name="subject
˓→
" maxlength="100" /></p>
<p><label for="message">Message:</label> <input type="text" name="message" id="message
˓→
" /></p>
<p><label for="sender">Sender:</label> <input type="text" name="sender" id="sender" />
˓→
</p>
<p><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself"
˓→ id="cc_myself" /></p>
If auto_id is set to a string containing the format character '%s', then the form output will include <label> tags, and will generate id attributes based on the format string. For example, for a format string 'field_%s', a field named subject will get the id value 'field_subject'. Continuing our example:
>>> f = ContactForm(auto_id= 'id_for_%s' )
>>> print (f.as_table())
<tr><th><label for="id_for_subject">Subject:</label></th><td><input id="id_for_subject
˓→
" type="text" name="subject" maxlength="100" /></td></tr>
<tr><th><label for="id_for_message">Message:</label></th><td><input type="text" name=
˓→
"message" id="id_for_message" /></td></tr>
<tr><th><label for="id_for_sender">Sender:</label></th><td><input type="text" name=
˓→
"sender" id="id_for_sender" /></td></tr>
<tr><th><label for="id_for_cc_myself">Cc myself:</label></th><td><input type="checkbox
˓→
" name="cc_myself" id="id_for_cc_myself" /></td></tr>
>>> print (f.as_ul())
<li><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text
˓→
" name="subject" maxlength="100" /></li>
<li><label for="id_for_message">Message:</label> <input type="text" name="message" id=
˓→
"id_for_message" /></li>
<li><label for="id_for_sender">Sender:</label> <input type="text" name="sender" id=
˓→
"id_for_sender" /></li>
<li><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_
˓→ myself" id="id_for_cc_myself" /></li>
>>> print (f.as_p())
<p><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text
˓→
" name="subject" maxlength="100" /></p>
<p><label for="id_for_message">Message:</label> <input type="text" name="message" id=
˓→
"id_for_message" /></p>
<p><label for="id_for_sender">Sender:</label> <input type="text" name="sender" id="id_
˓→ for_sender" /></p>
6.9. Forms 865
Django Documentation, Release 1.5.12
<p><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_
˓→ myself" id="id_for_cc_myself" /></p>
If auto_id is set to any other true value – such as a string that doesn’t include %s – then the library will act as if auto_id is True.
By default, auto_id is set to the string 'id_%s'.
Normally, a colon (:) will be appended after any label name when a form is rendered. It’s possible to change the colon to another character, or omit it entirely, using the label_suffix parameter:
>>> f = ContactForm(auto_id= 'id_for_%s' , label_suffix= '' )
>>> print (f.as_ul())
<li><label for="id_for_subject">Subject</label> <input id="id_for_subject" type="text
˓→
" name="subject" maxlength="100" /></li>
<li><label for="id_for_message">Message</label> <input type="text" name="message" id=
˓→
"id_for_message" /></li>
<li><label for="id_for_sender">Sender</label> <input type="text" name="sender" id="id_
˓→ for_sender" /></li>
<li><label for="id_for_cc_myself">Cc myself</label> <input type="checkbox" name="cc_
˓→ myself" id="id_for_cc_myself" /></li>
>>> f = ContactForm(auto_id= 'id_for_%s' , label_suffix= ' ->' )
>>> print (f.as_ul())
<li><label for="id_for_subject">Subject -></label> <input id="id_for_subject" type=
˓→
"text" name="subject" maxlength="100" /></li>
<li><label for="id_for_message">Message -></label> <input type="text" name="message"
˓→ id="id_for_message" /></li>
<li><label for="id_for_sender">Sender -></label> <input type="text" name="sender" id=
˓→
"id_for_sender" /></li>
<li><label for="id_for_cc_myself">Cc myself -></label> <input type="checkbox" name=
˓→
"cc_myself" id="id_for_cc_myself" /></li>
Note that the label suffix is added only if the last character of the label isn’t a punctuation character (., !, ? or :)
Notes on field ordering
In the as_p(), as_ul() and as_table() shortcuts, the fields are displayed in the order in which you define them in your form class. For example, in the ContactForm example, the fields are defined in the order subject, message
, sender, cc_myself. To reorder the HTML output, just change the order in which those fields are listed in the class.
How errors are displayed
If you render a bound Form object, the act of rendering will automatically run the form’s validation if it hasn’t already happened, and the HTML output will include the validation errors as a <ul class="errorlist"> near the field.
The particular positioning of the error messages depends on the output method you’re using:
>>> data = { 'subject' : '' ,
...
...
'message'
'sender' :
: 'Hi there' ,
'invalid email address' ,
...
'cc_myself' : True}
>>> f = ContactForm(data, auto_id=False)
>>> print (f.as_table())
<tr><th>Subject:</th><td><ul class="errorlist"><li>This field is required.</li></ul>
˓→
<input type="text" name="subject" maxlength="100" /></td></tr>
866 Chapter 6. API Reference
Django Documentation, Release 1.5.12
<tr><th>Message:</th><td><input type="text" name="message" value="Hi there" /></td></
˓→ tr>
<tr><th>Sender:</th><td><ul class="errorlist"><li>Enter a valid email address.</li></
˓→ ul><input type="text" name="sender" value="invalid email address" /></td></tr>
<tr><th>Cc myself:</th><td><input checked="checked" type="checkbox" name="cc_myself" /
˓→
></td></tr>
>>> print (f.as_ul())
<li><ul class="errorlist"><li>This field is required.</li></ul>Subject: <input type=
˓→
"text" name="subject" maxlength="100" /></li>
<li>Message: <input type="text" name="message" value="Hi there" /></li>
<li><ul class="errorlist"><li>Enter a valid email address.</li></ul>Sender: <input
˓→ type="text" name="sender" value="invalid email address" /></li>
<li>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></li>
>>> print (f.as_p())
<p><ul class="errorlist"><li>This field is required.</li></ul></p>
<p>Subject: <input type="text" name="subject" maxlength="100" /></p>
<p>Message: <input type="text" name="message" value="Hi there" /></p>
<p><ul class="errorlist"><li>Enter a valid email address.</li></ul></p>
<p>Sender: <input type="text" name="sender" value="invalid email address" /></p>
<p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p>
Customizing the error list format
By default, forms use django.forms.util.ErrorList to format validation errors. If you’d like to use an alternate class for displaying errors, you can pass that in at construction time:
>>>
from
django.forms.util
import
ErrorList
>>>
class DivErrorList
(ErrorList):
...
def __unicode__
( self ):
...
return
self
.
as_divs()
...
...
def as_divs
( self ):
if not
self : return u''
...
return
u'<div class="errorlist">%s</div>'
%
''
.
join([ u'<div class="error">
˓→
%s</div>'
%
e for e in self ])
>>> f = ContactForm(data, auto_id=False, error_class=DivErrorList)
>>> f.as_p()
<div class="errorlist"><div class="error">This field is required.</div></div>
<p>Subject: <input type="text" name="subject" maxlength="100" /></p>
<p>Message: <input type="text" name="message" value="Hi there" /></p>
<div class="errorlist"><div class="error">Enter a valid email address.</div></div>
<p>Sender: <input type="text" name="sender" value="invalid email address" /></p>
<p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p>
More granular output
The as_p(), as_ul() and as_table() methods are simply shortcuts for lazy developers – they’re not the only way a form object can be displayed.
class BoundField
Used to display HTML or access attributes for a single field of a
instance.
The __unicode__() and __str__() methods of this object displays the HTML for this field.
To retrieve a single BoundField, use dictionary lookup syntax on your form using the field’s name as the key:
6.9. Forms 867
Django Documentation, Release 1.5.12
>>> form = ContactForm()
>>> print (form[ 'subject' ])
<input id="id_subject" type="text" name="subject" maxlength="100" />
To retrieve all BoundField objects, iterate the form:
>>> form = ContactForm()
>>>
for
boundfield in form: print (boundfield)
<input id="id_subject" type="text" name="subject" maxlength="100" />
<input type="text" name="message" id="id_message" />
<input type="text" name="sender" id="id_sender" />
<input type="checkbox" name="cc_myself" id="id_cc_myself" />
The field-specific output honors the form object’s auto_id setting:
>>> f = ContactForm(auto_id=False)
>>> print (f[ 'message' ])
<input type="text" name="message" />
>>> f = ContactForm(auto_id= 'id_%s' )
>>> print (f[ 'message' ])
<input type="text" name="message" id="id_message" />
For a field’s list of errors, access the field’s errors attribute.
BoundField.errors
A list-like object that is displayed as an HTML <ul class="errorlist"> when printed:
>>> data = { 'subject' : 'hi' , 'message' : '' , 'sender' : '' , 'cc_myself' : '' }
>>> f = ContactForm(data, auto_id=False)
>>> print (f[ 'message' ])
<input type="text" name="message" />
>>> f[ 'message' ].errors
[u'This field is required.']
>>> print (f[ 'message' ].errors)
<ul class="errorlist"><li>This field is required.</li></ul>
>>> f[ 'subject' ].errors
[]
>>> print (f[ 'subject' ].errors)
>>> str (f[ 'subject' ].errors)
''
BoundField.label_tag( contents=None , attrs=None)
To separately render the label tag of a form field, you can call its label_tag method:
>>> f = ContactForm(data)
>>> print (f[ 'message' ].label_tag())
<label for="id_message">Message</label>
Optionally, you can provide the contents parameter which will replace the auto-generated label tag. An optional attrs dictionary may contain additional attributes for the <label> tag.
BoundField.css_classes()
When you use Django’s rendering shortcuts, CSS classes are used to indicate required form fields or fields that contain errors. If you’re manually rendering a form, you can access these CSS classes using the css_classes method:
868 Chapter 6. API Reference
Django Documentation, Release 1.5.12
>>> f = ContactForm(data)
>>> f[ 'message' ].css_classes()
'required'
If you want to provide some additional classes in addition to the error and required classes that may be required, you can provide those classes as an argument:
>>> f = ContactForm(data)
>>> f[ 'message' ].css_classes( 'foo bar' )
'foo bar required'
BoundField.value()
Use this method to render the raw value of this field as it would be rendered by a Widget:
>>> initial = { 'subject' : 'welcome' }
>>> unbound_form = ContactForm(initial=initial)
>>> bound_form = ContactForm(data, initial=initial)
>>> print (unbound_form[ 'subject' ].value()) welcome
>>> print (bound_form[ 'subject' ].value()) hi
BoundField.id_for_label
Use this property to render the ID of this field. For example, if you are manually constructing a <label> in your template (despite the fact that
will do this for you):
< label for
=
"
{{
form.my_field.id_for_label
}}
" >...</ label >
{{
my_field
}}
By default, this will be the field’s name prefixed by id_ (“id_my_field” for the example above). You may modify the ID by setting
on the field’s widget. For example, declaring a field like this: my_field = forms.CharField(widget=forms.TextInput(attrs={ 'id' : 'myFIELD' })) and using the template above, would render something like:
< label for
=
"myFIELD" >...</ label >< input id
=
"myFIELD" type
=
"text" name
=
"my_field" />
Binding uploaded files to a form
Dealing with forms that have FileField and ImageField fields is a little more complicated than a normal form.
Firstly, in order to upload files, you’ll need to make sure that your <form> element correctly defines the enctype as "multipart/form-data":
<
form enctype= "multipart/form-data" method= "post" action= "/foo/"
>
Secondly, when you use the form, you need to bind the file data. File data is handled separately to normal form data, so when your form contains a FileField and ImageField, you will need to specify a second argument when you bind your form. So if we extend our ContactForm to include an ImageField called mugshot, we need to bind the file data containing the mugshot image:
# Bound form with an image field
>>> from
django.core.files.uploadedfile
import
SimpleUploadedFile
>>>
data = { 'subject' : 'hello' ,
...
'message' : 'Hi there' ,
6.9. Forms 869
Django Documentation, Release 1.5.12
...
'sender' : '[email protected]' ,
...
'cc_myself' : True}
>>>
file_data = { 'mugshot' : SimpleUploadedFile( 'face.jpg' , <file data>)}
>>>
f = ContactFormWithMugshot(data, file_data)
In practice, you will usually specify request.FILES as the source of file data (just like you use request.POST
as the source of form data):
# Bound form with an image field, data from the request
>>>
f = ContactFormWithMugshot(request.POST, request.FILES)
Constructing an unbound form is the same as always – just omit both form data and file data:
# Unbound form with a image field
>>>
f = ContactFormWithMugshot()
Testing for multipart forms
Form.is_multipart()
If you’re writing reusable views or templates, you may not know ahead of time whether your form is a multipart form or not. The is_multipart() method tells you whether the form requires multipart encoding for submission:
>>> f = ContactFormWithMugshot()
>>> f.is_multipart()
True
Here’s an example of how you might use this in a template:
{% if form.is_multipart %}
<
form enctype= "multipart/form-data" method= "post" action= "/foo/"
>
{% else %}
<
form method= "post" action= "/foo/"
>
{% endif %}
{{ form }}
</
form>
Subclassing forms
If you have multiple Form classes that share fields, you can use subclassing to remove redundancy.
When you subclass a custom Form class, the resulting subclass will include all fields of the parent class(es), followed by the fields you define in the subclass.
In this example, ContactFormWithPriority contains all the fields from ContactForm, plus an additional field, priority. The ContactForm fields are ordered first:
>>>
class ContactFormWithPriority
(ContactForm):
...
priority = forms.CharField()
>>> f = ContactFormWithPriority(auto_id=False)
>>> print (f.as_ul())
<li>Subject: <input type="text" name="subject" maxlength="100" /></li>
<li>Message: <input type="text" name="message" /></li>
<li>Sender: <input type="text" name="sender" /></li>
870 Chapter 6. API Reference
Django Documentation, Release 1.5.12
<li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
<li>Priority: <input type="text" name="priority" /></li>
It’s possible to subclass multiple forms, treating forms as “mix-ins.” In this example, BeatleForm subclasses both
PersonForm and InstrumentForm (in that order), and its field list includes the fields from the parent classes:
>>>
class PersonForm
(Form):
...
first_name = CharField()
...
last_name = CharField()
>>>
class InstrumentForm
(Form):
...
instrument = CharField()
>>>
class BeatleForm
(PersonForm, InstrumentForm):
...
haircut_type = CharField()
>>> b = BeatleForm(auto_id=False)
>>> print (b.as_ul())
<li>First name: <input type="text" name="first_name" /></li>
<li>Last name: <input type="text" name="last_name" /></li>
<li>Instrument: <input type="text" name="instrument" /></li>
<li>Haircut type: <input type="text" name="haircut_type" /></li>
Prefixes for forms
Form.prefix
You can put several Django forms inside one <form> tag. To give each Form its own namespace, use the prefix keyword argument:
>>> mother = PersonForm(prefix= "mother" )
>>> father = PersonForm(prefix= "father" )
>>> print (mother.as_ul())
<li><label for="id_mother-first_name">First name:</label> <input type="text" name=
˓→
"mother-first_name" id="id_mother-first_name" /></li>
<li><label for="id_mother-last_name">Last name:</label> <input type="text" name=
˓→
"mother-last_name" id="id_mother-last_name" /></li>
>>> print (father.as_ul())
<li><label for="id_father-first_name">First name:</label> <input type="text" name=
˓→
"father-first_name" id="id_father-first_name" /></li>
<li><label for="id_father-last_name">Last name:</label> <input type="text" name=
˓→
"father-last_name" id="id_father-last_name" /></li>
Form fields
class Field(**kwargs)
When you create a Form class, the most important part is defining the fields of the form. Each field has custom validation logic, along with a few other hooks.
Field.clean( value)
Although the primary way you’ll use Field classes is in Form classes, you can also instantiate them and use them directly to get a better idea of how they work. Each Field instance has a clean() method, which takes a single argument and either raises a django.forms.ValidationError exception or returns the clean value:
>>>
from
django
import
forms
>>> f = forms.EmailField()
>>> f.clean( '[email protected]' )
6.9. Forms 871
Django Documentation, Release 1.5.12
>>> f.clean( 'invalid email address' )
Traceback (most recent call last):
...
ValidationError : [u'Enter a valid email address.']
Core field arguments
Each Field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:
required
Field.required
By default, each Field class assumes the value is required, so if you pass an empty value – either None or the empty string ("") – then clean() will raise a ValidationError exception:
>>> f = forms.CharField()
>>> f.clean( 'foo' ) u'foo'
>>> f.clean( '' )
Traceback (most recent call last):
...
ValidationError : [u'This field is required.']
>>> f.clean(None)
Traceback (most recent call last):
...
ValidationError : [u'This field is required.']
>>> f.clean( ' ' ) u' '
>>> f.clean( 0 ) u'0'
>>> f.clean(True) u'True'
>>> f.clean(False) u'False'
To specify that a field is not required, pass required=False to the Field constructor:
>>> f = forms.CharField(required=False)
>>> f.clean( 'foo' ) u'foo'
>>> f.clean( '' ) u''
>>> f.clean(None) u''
>>> f.clean( 0 ) u'0'
>>> f.clean(True) u'True'
>>> f.clean(False) u'False'
872 Chapter 6. API Reference
Django Documentation, Release 1.5.12
If a Field has required=False and you pass clean() an empty value, then clean() will return a normalized empty value rather than raising ValidationError. For CharField, this will be a Unicode empty string. For other Field classes, it might be None. (This varies from field to field.)
label
Field.label
The label argument lets you specify the “human-friendly” label for this field. This is used when the Field is displayed in a Form.
As explained in “Outputting forms as HTML” above, the default label for a Field is generated from the field name by converting all underscores to spaces and upper-casing the first letter. Specify label if that default behavior doesn’t result in an adequate label.
Here’s a full example Form that implements label for two of its fields. We’ve specified auto_id=False to simplify the output:
>>>
class CommentForm
(forms.Form):
...
...
name = forms.CharField(label= url = forms.URLField(label=
'Your name' )
'Your Web site' , required=False)
...
comment = forms.CharField()
>>> f = CommentForm(auto_id=False)
>>> print (f)
<tr><th>Your name:</th><td><input type="text" name="name" /></td></tr>
<tr><th>Your Web site:</th><td><input type="text" name="url" /></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
initial
Field.initial
The initial argument lets you specify the initial value to use when rendering this Field in an unbound Form.
To specify dynamic initial data, see the
parameter.
The use-case for this is when you want to display an “empty” form in which a field is initialized to a particular value.
For example:
>>>
class CommentForm
(forms.Form):
...
name = forms.CharField(initial= 'Your name' )
...
...
url = forms.URLField(initial= comment = forms.CharField()
'http://' )
>>> f = CommentForm(auto_id=False)
>>> print (f)
<tr><th>Name:</th><td><input type="text" name="name" value="Your name" /></td></tr>
<tr><th>Url:</th><td><input type="text" name="url" value="http://" /></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
You may be thinking, why not just pass a dictionary of the initial values as data when displaying the form? Well, if you do that, you’ll trigger validation, and the HTML output will include any validation errors:
>>>
class CommentForm
(forms.Form):
...
name = forms.CharField()
...
...
url = forms.URLField() comment = forms.CharField()
>>> default_data = { 'name' : 'Your name' , 'url' : 'http://' }
6.9. Forms 873
Django Documentation, Release 1.5.12
>>> f = CommentForm(default_data, auto_id=False)
>>> print (f)
<tr><th>Name:</th><td><input type="text" name="name" value="Your name" /></td></tr>
<tr><th>Url:</th><td><ul class="errorlist"><li>Enter a valid URL.</li></ul><input
˓→ type="text" name="url" value="http://" /></td></tr>
<tr><th>Comment:</th><td><ul class="errorlist"><li>This field is required.</li></ul>
˓→
<input type="text" name="comment" /></td></tr>
This is why initial values are only displayed for unbound forms. For bound forms, the HTML output will use the bound data.
Also note that initial values are not used as “fallback” data in validation if a particular field’s value is not given.
initial values are only intended for initial form display:
>>>
class CommentForm
(forms.Form):
...
name = forms.CharField(initial= 'Your name' )
...
url = forms.URLField(initial= 'http://' )
...
comment = forms.CharField()
>>> data = { 'name' : '' , 'url' : '' , 'comment' : 'Foo' }
>>> f = CommentForm(data)
>>> f.is_valid()
False
# The form does *not* fall back to using the initial values.
>>> f.errors
{'url': [u'This field is required.'], 'name': [u'This field is required.']}
Instead of a constant, you can also pass any callable:
>>>
import
datetime
>>>
class DateForm
(forms.Form):
...
day = forms.DateField(initial=datetime.date.today)
>>> print (DateForm())
<tr><th>Day:</th><td><input type="text" name="day" value="12/23/2008" /><td></tr>
The callable will be evaluated only when the unbound form is displayed, not when it is defined.
widget
Field.widget
The widget argument lets you specify a Widget class to use when rendering this Field. See
for more information.
help_text
Field.help_text
The help_text argument lets you specify descriptive text for this Field. If you provide help_text, it will be displayed next to the Field when the Field is rendered by one of the convenience Form methods (e.g., as_ul()).
Here’s a full example Form that implements help_text for two of its fields. We’ve specified auto_id=False to simplify the output:
>>>
class HelpTextContactForm
(forms.Form):
...
...
subject = forms.CharField(max_length= message = forms.CharField()
100 , help_text= '100 characters max.' )
874 Chapter 6. API Reference
Django Documentation, Release 1.5.12
...
sender = forms.EmailField(help_text= 'A valid email address, please.' )
...
cc_myself = forms.BooleanField(required=False)
>>> f = HelpTextContactForm(auto_id=False)
>>> print (f.as_table())
<tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /><br />
˓→
<span class="helptext">100 characters max.</span></td></tr>
<tr><th>Message:</th><td><input type="text" name="message" /></td></tr>
<tr><th>Sender:</th><td><input type="text" name="sender" /><br />A valid email
˓→ address, please.</td></tr>
<tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr>
>>> print (f.as_ul()))
<li>Subject: <input type="text" name="subject" maxlength="100" /> <span class=
˓→
"helptext">100 characters max.</span></li>
<li>Message: <input type="text" name="message" /></li>
<li>Sender: <input type="text" name="sender" /> A valid email address, please.</li>
<li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
>>> print (f.as_p())
<p>Subject: <input type="text" name="subject" maxlength="100" /> <span class="helptext
˓→
">100 characters max.</span></p>
<p>Message: <input type="text" name="message" /></p>
<p>Sender: <input type="text" name="sender" /> A valid email address, please.</p>
<p>Cc myself: <input type="checkbox" name="cc_myself" /></p>
error_messages
Field.error_messages
The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override. For example, here is the default error message:
>>> generic = forms.CharField()
>>> generic.clean( '' )
Traceback (most recent call last):
...
ValidationError : [u'This field is required.']
And here is a custom error message:
>>> name = forms.CharField(error_messages={ 'required' : 'Please enter your name' })
>>> name.clean( '' )
Traceback (most recent call last):
...
ValidationError : [u'Please enter your name']
In the
section below, each Field defines the error message keys it uses.
validators
Field.validators
The validators argument lets you provide a list of validation functions for this field.
See the
for more information.
6.9. Forms 875
Django Documentation, Release 1.5.12
localize
Field.localize
The localize argument enables the localization of form data, input as well as the rendered output.
See the
documentation for more information.
Built-in Field classes
Naturally, the forms library comes with a set of Field classes that represent common validation needs. This section documents each built-in field.
For each field, we describe the default widget used if you don’t specify widget. We also specify the value returned when you provide an empty value (see the section on required above to understand what that means).
BooleanField
class BooleanField(**kwargs)
•Default widget:
•Empty value: False
•Normalizes to: A Python True or False value.
•Validates that the value is True (e.g. the check box is checked) if the field has required=True.
•Error message keys: required
Note:
Since all Field subclasses have required=True by default, the validation condition here is important. If you want to include a boolean in your form that can be either True or False (e.g. a checked or unchecked checkbox), you must remember to pass in required=False when creating the BooleanField.
CharField
class CharField(**kwargs)
•Default widget:
•Empty value: '' (an empty string)
•Normalizes to: A Unicode object.
•Validates max_length or min_length, if they are provided. Otherwise, all inputs are valid.
•Error message keys: required, max_length, min_length
Has two optional arguments for validation:
max_length min_length
If provided, these arguments ensure that the string is at most or at least the given length.
876 Chapter 6. API Reference
Django Documentation, Release 1.5.12
ChoiceField
class ChoiceField(**kwargs)
•Default widget:
•Empty value: '' (an empty string)
•Normalizes to: A Unicode object.
•Validates that the given value exists in the list of choices.
•Error message keys: required, invalid_choice
The invalid_choice error message may contain %(value)s, which will be replaced with the selected choice.
Takes one extra required argument:
choices
An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field. This argument accepts the same formats as the choices argument to a model field. See the
model field reference documentation on choices
for more details.
TypedChoiceField
class TypedChoiceField(**kwargs)
Just like a
takes two extra arguments, coerce and empty_value
.
•Default widget:
•Empty value: Whatever you’ve given as empty_value
•Normalizes to: A value of the type provided by the coerce argument.
•Validates that the given value exists in the list of choices and can be coerced.
•Error message keys: required, invalid_choice
Takes extra arguments:
coerce
A function that takes one argument and returns a coerced value. Examples include the built-in int, float
, bool and other types. Defaults to an identity function.
empty_value
The value to use to represent “empty.” Defaults to the empty string; None is another common choice here. Note that this value will not be coerced by the function given in the coerce argument, so choose it accordingly.
DateField
class DateField(**kwargs)
•Default widget:
•Empty value: None
•Normalizes to: A Python datetime.date object.
6.9. Forms 877
Django Documentation, Release 1.5.12
•Validates that the given value is either a datetime.date, datetime.datetime or string formatted in a particular date format.
•Error message keys: required, invalid
Takes one optional argument:
input_formats
A list of formats used to attempt to convert a string to a valid datetime.date object.
If no input_formats argument is provided, the default input formats are:
'%Y-%m-%d' ,
'%m/%d/%Y' ,
'%m/%d/%y' ,
# '2006-10-25'
# '10/25/2006'
# '10/25/06'
Additionally, if you specify
in your settings, the following will also be included in the default input formats:
'%b %d %Y' ,
'%b %d, %Y' ,
'%d %b %Y' ,
'%d %b, %Y' ,
'%B %d %Y' ,
'%B %d, %Y' ,
'%d %B %Y' ,
'%d %B, %Y' ,
# 'Oct 25 2006'
# 'Oct 25, 2006'
# '25 Oct 2006'
# '25 Oct, 2006'
# 'October 25 2006'
# 'October 25, 2006'
# '25 October 2006'
# '25 October, 2006'
See also
DateTimeField
class DateTimeField(**kwargs)
•Default widget:
•Empty value: None
•Normalizes to: A Python datetime.datetime object.
•Validates that the given value is either a datetime.datetime, datetime.date or string formatted in a particular datetime format.
•Error message keys: required, invalid
Takes one optional argument:
input_formats
A list of formats used to attempt to convert a string to a valid datetime.datetime object.
If no input_formats argument is provided, the default input formats are:
'%Y-%m-%d %H:%M:%S' ,
'%Y-%m-%d %H:%M' ,
'%Y-%m-%d' ,
'%m/%d/%Y %H:%M:%S' ,
'%m/%d/%Y %H:%M' ,
'%m/%d/%Y' ,
'%m/%d/%y %H:%M:%S' ,
'%m/%d/%y %H:%M' ,
'%m/%d/%y' ,
# '2006-10-25 14:30:59'
# '2006-10-25 14:30'
# '2006-10-25'
# '10/25/2006 14:30:59'
# '10/25/2006 14:30'
# '10/25/2006'
# '10/25/06 14:30:59'
# '10/25/06 14:30'
# '10/25/06'
878 Chapter 6. API Reference
Django Documentation, Release 1.5.12
See also
DecimalField
class DecimalField(**kwargs)
•Default widget:
•Empty value: None
•Normalizes to: A Python decimal.
•Validates that the given value is a decimal. Leading and trailing whitespace is ignored.
•Error message keys: required
, invalid
, max_value
, min_value
, max_digits
, max_decimal_places
, max_whole_digits
The max_value and min_value error messages may contain %(limit_value)s, which will be substituted by the appropriate limit.
Takes four optional arguments:
max_value min_value
These control the range of values permitted in the field, and should be given as decimal.Decimal
values.
max_digits
The maximum number of digits (those before the decimal point plus those after the decimal point, with leading zeros stripped) permitted in the value.
decimal_places
The maximum number of decimal places permitted.
EmailField
class EmailField(**kwargs)
•Default widget:
•Empty value: '' (an empty string)
•Normalizes to: A Unicode object.
•Validates that the given value is a valid email address, using a moderately complex regular expression.
•Error message keys: required, invalid
Has two optional arguments for validation, max_length and min_length. If provided, these arguments ensure that the string is at most or at least the given length.
FileField
class FileField(**kwargs)
•Default widget:
•Empty value: None
•Normalizes to: An UploadedFile object that wraps the file content and file name into a single object.
6.9. Forms 879
Django Documentation, Release 1.5.12
•Can validate that non-empty file data has been bound to the form.
•Error message keys: required, invalid, missing, empty, max_length
Has two optional arguments for validation, max_length and allow_empty_file. If provided, these ensure that the file name is at most the given length, and that validation will succeed even if the file content is empty.
To learn more about the UploadedFile object, see the
When you use a FileField in a form, you must also remember to
bind the file data to the form .
The max_length error refers to the length of the filename. In the error message for that key, %(max)d will be replaced with the maximum filename length and %(length)d will be replaced with the current filename length.
FilePathField
class FilePathField(**kwargs)
•Default widget:
•Empty value: None
•Normalizes to: A unicode object
•Validates that the selected choice exists in the list of choices.
•Error message keys: required, invalid_choice
The field allows choosing from files inside a certain directory. It takes three extra arguments; only path is required:
path
The absolute path to the directory whose contents you want listed. This directory must exist.
recursive
If False (the default) only the direct contents of path will be offered as choices. If True, the directory will be descended into recursively and all descendants will be listed as choices.
match
A regular expression pattern; only files with names matching this expression will be allowed as choices.
allow_files
Optional. Either True or False. Default is True. Specifies whether files in the specified location should be included. Either this or
must be True.
allow_folders
Optional. Either True or False. Default is False. Specifies whether folders in the specified location should be included. Either this or
must be True.
FloatField
class FloatField(**kwargs)
•Default widget:
•Empty value: None
•Normalizes to: A Python float.
880 Chapter 6. API Reference
Django Documentation, Release 1.5.12
•Validates that the given value is an float. Leading and trailing whitespace is allowed, as in Python’s float() function.
•Error message keys: required, invalid, max_value, min_value
Takes two optional arguments for validation, max_value and min_value. These control the range of values permitted in the field.
ImageField
class ImageField(**kwargs)
•Default widget:
•Empty value: None
•Normalizes to: An UploadedFile object that wraps the file content and file name into a single object.
•Validates that file data has been bound to the form, and that the file is of an image format understood by
PIL.
•Error message keys: required, invalid, missing, empty, invalid_image
Using an ImageField requires that the Python Imaging Library (PIL) is installed and supports the image formats you use. If you encounter a corrupt image error when you upload an image, it usually means PIL doesn’t understand its format. To fix this, install the appropriate library and reinstall PIL.
When you use an ImageField on a form, you must also remember to
bind the file data to the form .
IntegerField
class IntegerField(**kwargs)
•Default widget:
•Empty value: None
•Normalizes to: A Python integer or long integer.
•Validates that the given value is an integer. Leading and trailing whitespace is allowed, as in Python’s int() function.
•Error message keys: required, invalid, max_value, min_value
The max_value and min_value error messages may contain %(limit_value)s, which will be substituted by the appropriate limit.
Takes two optional arguments for validation:
max_value min_value
These control the range of values permitted in the field.
IPAddressField
class IPAddressField(**kwargs)
•Default widget:
6.9. Forms 881
Django Documentation, Release 1.5.12
•Empty value: '' (an empty string)
•Normalizes to: A Unicode object.
•Validates that the given value is a valid IPv4 address, using a regular expression.
•Error message keys: required, invalid
GenericIPAddressField
class GenericIPAddressField(**kwargs)
A field containing either an IPv4 or an IPv6 address.
•Default widget:
•Empty value: '' (an empty string)
•Normalizes to: A Unicode object. IPv6 addresses are normalized as described below.
•Validates that the given value is a valid IP address.
•Error message keys: required, invalid
The IPv6 address normalization follows RFC 4291#section-2.2
section 2.2, including using the IPv4 format suggested in paragraph 3 of that section, like ::ffff:192.0.2.0. For example, 2001:0::0:01 would be normalized to 2001::1, and ::ffff:0a0a:0a0a to ::ffff:10.10.10.10. All characters are converted to lowercase.
Takes two optional arguments:
protocol
Limits valid inputs to the specified protocol. Accepted values are both (default), IPv4 or IPv6. Matching is case insensitive.
unpack_ipv4
Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.
MultipleChoiceField
class MultipleChoiceField(**kwargs)
•Default widget:
•Empty value: [] (an empty list)
•Normalizes to: A list of Unicode objects.
•Validates that every value in the given list of values exists in the list of choices.
•Error message keys: required, invalid_choice, invalid_list
The invalid_choice error message may contain %(value)s, which will be replaced with the selected choice.
Takes one extra required argument, choices, as for ChoiceField.
882 Chapter 6. API Reference
Django Documentation, Release 1.5.12
TypedMultipleChoiceField
class TypedMultipleChoiceField(**kwargs)
Just like a
takes two extra arguments, coerce and empty_value.
•Default widget:
•Empty value: Whatever you’ve given as empty_value
•Normalizes to: A list of values of the type provided by the coerce argument.
•Validates that the given values exists in the list of choices and can be coerced.
•Error message keys: required, invalid_choice
The invalid_choice error message may contain %(value)s, which will be replaced with the selected choice.
Takes two extra arguments, coerce and empty_value, as for TypedChoiceField.
NullBooleanField
class NullBooleanField(**kwargs)
•Default widget:
•Empty value: None
•Normalizes to: A Python True, False or None value.
•Validates nothing (i.e., it never raises a ValidationError).
RegexField
class RegexField(**kwargs)
•Default widget:
•Empty value: '' (an empty string)
•Normalizes to: A Unicode object.
•Validates that the given value matches against a certain regular expression.
•Error message keys: required, invalid
Takes one required argument:
regex
A regular expression specified either as a string or a compiled regular expression object.
Also takes max_length and min_length, which work just as they do for CharField.
The optional argument error_message is also accepted for backwards compatibility. The preferred way to provide an error message is to use the error_messages argument, passing a dictionary with 'invalid' as a key and the error message as the value.
6.9. Forms 883
Django Documentation, Release 1.5.12
SlugField
class SlugField(**kwargs)
•Default widget:
•Empty value: '' (an empty string)
•Normalizes to: A Unicode object.
•Validates that the given value contains only letters, numbers, underscores, and hyphens.
•Error messages: required, invalid
This field is intended for use in representing a model
in forms.
TimeField
class TimeField(**kwargs)
•Default widget:
•Empty value: None
•Normalizes to: A Python datetime.time object.
•Validates that the given value is either a datetime.time or string formatted in a particular time format.
•Error message keys: required, invalid
Takes one optional argument:
input_formats
A list of formats used to attempt to convert a string to a valid datetime.time object.
If no input_formats argument is provided, the default input formats are:
'%H:%M:%S' ,
'%H:%M' ,
# '14:30:59'
# '14:30'
URLField
class URLField(**kwargs)
•Default widget:
•Empty value: '' (an empty string)
•Normalizes to: A Unicode object.
•Validates that the given value is a valid URL.
•Error message keys: required, invalid
Takes the following optional arguments:
max_length min_length
These are the same as CharField.max_length and CharField.min_length.
884 Chapter 6. API Reference
Django Documentation, Release 1.5.12
Slightly complex built-in Field classes
ComboField
class ComboField(**kwargs)
•Default widget:
•Empty value: '' (an empty string)
•Normalizes to: A Unicode object.
•Validates that the given value against each of the fields specified as an argument to the ComboField.
•Error message keys: required, invalid
Takes one extra required argument:
fields
The list of fields that should be used to validate the field’s value (in the order in which they are provided).
>>> f = ComboField(fields=[CharField(max_length= 20 ), EmailField()])
>>> f.clean( '[email protected]' ) u'[email protected]'
>>> f.clean( '[email protected]' )
Traceback (most recent call last):
...
ValidationError : [u'Ensure this value has at most 20 characters (it has 28).']
MultiValueField
class MultiValueField(fields=(), **kwargs)
•Default widget:
•Empty value: '' (an empty string)
•Normalizes to: the type returned by the compress method of the subclass.
•Validates that the given value against each of the fields specified as an argument to the
MultiValueField
.
•Error message keys: required, invalid
Aggregates the logic of multiple fields that together produce a single value.
This field is abstract and must be subclassed.
In contrast with the single-value fields, subclasses of
must not implement
but instead - implement
Takes one extra required argument:
fields
A tuple of fields whose values are cleaned and subsequently combined into a single value. Each value of the field is cleaned by the corresponding field in fields – the first value is cleaned by the first field, the second value is cleaned by the second field, etc. Once all fields are cleaned, the list of clean values is combined into a single value by
widget
Must be a subclass of
is not very useful in this case.
6.9. Forms 885
Django Documentation, Release 1.5.12
compress
( data_list)
Takes a list of valid values and returns a “compressed” version of those values – in a single value. For example,
is a subclass which combines a time field and a date field into a datetime object.
This method must be implemented in the subclasses.
SplitDateTimeField
class SplitDateTimeField(**kwargs)
•Default widget:
•Empty value: None
•Normalizes to: A Python datetime.datetime object.
•Validates that the given value is a datetime.datetime or string formatted in a particular datetime format.
•Error message keys: required, invalid, invalid_date, invalid_time
Takes two optional arguments:
input_date_formats
A list of formats used to attempt to convert a string to a valid datetime.date object.
If no input_date_formats argument is provided, the default input formats for DateField are used.
input_time_formats
A list of formats used to attempt to convert a string to a valid datetime.time object.
If no input_time_formats argument is provided, the default input formats for TimeField are used.
Fields which handle relationships
Two fields are available for representing relationships between models:
and
. Both of these fields require a single queryset parameter that is used to
create the choices for the field. Upon form validation, these fields will place either one model object (in the case of ModelChoiceField) or multiple model objects (in the case of ModelMultipleChoiceField) into the cleaned_data dictionary of the form.
ModelChoiceField
class ModelChoiceField(**kwargs)
•Default widget:
•Empty value: None
•Normalizes to: A model instance.
•Validates that the given id exists in the queryset.
•Error message keys: required, invalid_choice
Allows the selection of a single model object, suitable for representing a foreign key. Note that the default widget for ModelChoiceField becomes impractical when the number of entries increases. You should avoid using it for more than 100 items.
886 Chapter 6. API Reference
Django Documentation, Release 1.5.12
A single argument is required:
queryset
A QuerySet of model objects from which the choices for the field will be derived, and which will be used to validate the user’s selection.
ModelChoiceField also takes one optional argument:
empty_label
By default the <select> widget used by ModelChoiceField will have an empty choice at the top of the list. You can change the text of this label (which is "---------" by default) with the empty_label attribute, or you can disable the empty label entirely by setting empty_label to None:
# A custom empty label field1 = forms.ModelChoiceField(queryset=..., empty_label= "(Nothing)" )
# No empty label field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
Note that if a ModelChoiceField is required and has a default initial value, no empty choice is created
(regardless of the value of empty_label).
The __unicode__ method of the model will be called to generate string representations of the objects for use in the field’s choices; to provide customized representations, subclass ModelChoiceField and override label_from_instance . This method will receive a model object, and should return a string suitable for representing it. For example:
class MyModelChoiceField
(ModelChoiceField):
def label_from_instance
( self , obj):
return
"My Object #%i"
%
obj.id
ModelMultipleChoiceField
class ModelMultipleChoiceField(**kwargs)
•Default widget:
•Empty value: An empty QuerySet (self.queryset.none())
•Normalizes to: A QuerySet of model instances.
•Validates that every id in the given list of values exists in the queryset.
•Error message keys: required, list, invalid_choice, invalid_pk_value
The empty and normalized values were changed to be consistently QuerySets instead of [] and QuerySet respectively. Allows the selection of one or more model objects, suitable for representing a many-to-many relation. As with
, you can use label_from_instance to customize the object
representations, and queryset is a required parameter:
queryset
A QuerySet of model objects from which the choices for the field will be derived, and which will be used to validate the user’s selection.
Creating custom fields
If the built-in Field classes don’t meet your needs, you can easily create custom Field classes. To do this, just create a subclass of django.forms.Field. Its only requirements are that it implement a clean() method
6.9. Forms 887
Django Documentation, Release 1.5.12
and that its __init__() method accept the core arguments mentioned above (required, label, initial, widget
, help_text).
Model Form Functions
modelform_factory
( model , form=ModelForm, fields=None, exclude=None, formfield_callback=None, widgets=None)
Returns a
class for the given model. You can optionally pass a form argument to use as a starting point for constructing the ModelForm.
fields is an optional list of field names. If provided, only the named fields will be included in the returned fields.
exclude is an optional list of field names. If provided, the named fields will be excluded from the returned fields, even if they are listed in the fields argument.
widgets is a dictionary of model field names mapped to a widget.
formfield_callback is a callable that takes a model field and returns a form field.
See
for example usage.
modelformset_factory
( model , form=ModelForm , formfield_callback=None , formset=BaseModelFormSet , extra=1 , can_delete=False , can_order=False , max_num=None , fields=None, exclude=None)
Returns a FormSet class for the given model class.
Arguments model, form, fields, exclude, and formfield_callback are all passed through to
Arguments formset, extra, max_num, can_order, and can_delete are passed through to formset_factory
. See
for details.
See
for example usage.
inlineformset_factory
( parent_model , model , form=ModelForm , formset=BaseInlineFormSet , fk_name=None , fields=None, exclude=None, extra=3, can_order=False, can_delete=True , max_num=None, formfield_callback=None)
Returns an
InlineFormSet using
with defaults of
, can_delete=True, and extra=3.
If your model has more than one
to the parent_model, you must specify a fk_name.
See
for example usage.
Widgets
A widget is Django’s representation of a HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget.
Tip: Widgets should not be confused with the
form fields . Form fields deal with the logic of input validation and are
used directly in templates. Widgets deal with rendering of HTML form input elements on the web page and extraction of raw submitted data. However, widgets do need to be
to form fields.
888 Chapter 6. API Reference
Django Documentation, Release 1.5.12
Specifying widgets
Whenever you specify a field on a form, Django will use a default widget that is appropriate to the type of data that is to be displayed. To find which widget is used on which field, see the documentation about
However, if you want to use a different widget for a field, you can just use the
argument on the field definition.
For example:
from
django
import
forms
class CommentForm
(forms.Form): name = forms.CharField() url = forms.URLField() comment = forms.CharField(widget=forms.Textarea)
This would specify a form with a comment that uses a larger
widget, rather than the default
widget.
Setting arguments for widgets
Many widgets have optional extra arguments; they can be set when defining the widget on the field. In the following example, the
attribute is set for a
from
django
import
forms
from
django.forms.extras.widgets
import
SelectDateWidget
BIRTH_YEAR_CHOICES = ( '1980' , '1981' , '1982' )
FAVORITE_COLORS_CHOICES = (( 'blue' , 'Blue' ),
( 'green' , 'Green' ),
( 'black' , 'Black' ))
class SimpleForm
(forms.Form): birth_year = forms.DateField(widget=SelectDateWidget(years=BIRTH_YEAR_CHOICES)) favorite_colors = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES)
See the
for more information about which widgets are available and which arguments they accept.
Widgets inheriting from the Select widget
Widgets inheriting from the
widget deal with choices. They present the user with a list of options to choose from. The different widgets present this choice differently; the
widget itself uses a <select> HTML list representation, while
uses radio buttons.
widgets are used by default on
fields. The choices displayed on the widget are inherited from the
and changing
will update
>>>
from
django
import
forms
>>> CHOICES = (( '1' , 'First' ,), ( '2' , 'Second' ,))
>>> choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
>>> choice_field.choices
[('1', 'First'), ('2', 'Second')]
>>> choice_field.widget.choices
[('1', 'First'), ('2', 'Second')]
>>> choice_field.widget.choices = ()
>>> choice_field.choices = (( '1' , 'First and only' ,),)
6.9. Forms 889
Django Documentation, Release 1.5.12
>>> choice_field.widget.choices
[('1', 'First and only')]
Widgets which offer a
attribute can however be used with fields which are not based on choice – such as a
– but it is recommended to use a
-based field when the choices are inherent to the model
and not just the representational widget.
Customizing widget instances
When Django renders a widget as HTML, it only renders very minimal markup - Django doesn’t add class names, or any other widget-specific attributes. This means, for example, that all
widgets will appear the same on your Web pages.
There are two ways to customize widgets:
and
Styling widget instances
If you want to make one widget instance look different from another, you will need to specify additional attributes at the time when the widget object is instantiated and assigned to a form field (and perhaps add some rules to your CSS files).
For example, take the following simple form:
from
django
import
forms
class CommentForm
(forms.Form): name = forms.CharField() url = forms.URLField() comment = forms.CharField()
This form will include three default
widgets, with default rendering – no CSS class, no extra attributes.
This means that the input boxes provided for each widget will be rendered exactly the same:
>>> f = CommentForm(auto_id=False)
>>> f.as_table()
<tr><th>Name:</th><td><input type="text" name="name" /></td></tr>
<tr><th>Url:</th><td><input type="text" name="url"/></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
On a real Web page, you probably don’t want every widget to look the same. You might want a larger input element for the comment, and you might want the ‘name’ widget to have some special CSS class. It is also possible to specify the
‘type’ attribute to take advantage of the new HTML5 input types. To do this, you use the
argument when creating the widget:
class CommentForm
(forms.Form): name = forms.CharField( widget=forms.TextInput(attrs={ 'class' : 'special' })) url = forms.URLField() comment = forms.CharField( widget=forms.TextInput(attrs={ 'size' : '40' }))
Django will then include the extra attributes in the rendered output:
>>> f = CommentForm(auto_id=False)
>>> f.as_table()
890 Chapter 6. API Reference
Django Documentation, Release 1.5.12
<tr><th>Name:</th><td><input type="text" name="name" class="special"/></td></tr>
<tr><th>Url:</th><td><input type="text" name="url"/></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" size="40"/></td></tr>
You can also set the HTML id using
for an example.
Styling widget classes
With widgets, it is possible to add media (css and javascript) and more deeply customize their appearance and behavior.
In a nutshell, you will need to subclass the widget and either
as a member of the subclass, or
create a property “media” , returning an instance of that class.
These methods involve somewhat advanced Python programming and are described in detail in the
topic guide.
Base Widget classes
Base widget classes
and
are subclassed by all the
and may serve as a foundation for custom widgets.
class Widget(attrs=None)
This abstract class cannot be rendered, but provides the basic attribute
attrs . You may also implement or
override the
method on custom widgets.
attrs
A dictionary containing HTML attributes to be set on the rendered widget.
>>> name = forms.TextInput(attrs={ 'size' : 10 , 'title' : 'Your name' ,})
>>> name.render( 'name' , 'A name' ) u'<input title="Your name" type="text" name="name" value="A name" size="10" />
˓→
'
render
( name , value, attrs=None)
Returns HTML for the widget, as a Unicode string. This method must be implemented by the subclass, otherwise NotImplementedError will be raised.
The ‘value’ given is not guaranteed to be valid input, therefore subclass implementations should program defensively.
value_from_datadict
( data , files, name)
Given a dictionary of data and this widget’s name, returns the value of this widget. Returns None if a value wasn’t provided.
class MultiWidget(widgets, attrs=None)
A widget that is composed of multiple widgets.
works hand in hand with the
has one required argument:
widgets
An iterable containing the widgets needed.
And one required method:
6.9. Forms 891
Django Documentation, Release 1.5.12
decompress
( value)
This method takes a single “compressed” value from the field and returns a list of “decompressed” values.
The input value can be assumed valid, but not necessarily non-empty.
This method must be implemented by the subclass, and since the value may be empty, the implementation must be defensive.
The rationale behind “decompression” is that it is necessary to “split” the combined value of the form field into the values for each widget.
An example of this is how
turns a datetime value into a list with date and time split into two separate values:
from
django.forms
import
MultiWidget
class SplitDateTimeWidget
(MultiWidget):
# ...
def decompress
( self , value):
if
value:
return
[value.date(), value.time().replace(microsecond= 0 )]
return
[None, None]
Tip: Note that
has a complementary method
with the opposite responsibility - to combine cleaned values of all member fields into one.
Other methods that may be useful to override include:
render
( name , value, attrs=None)
Argument value is handled differently in this method from the subclasses of
because it has to figure out how to split a single value for display in multiple widgets.
The value argument used when rendering can be one of two things:
•A list.
•A single value (e.g., a string) that is the “compressed” representation of a list of values.
If value is a list, the output of
will be a concatenation of rendered child widgets. If value is not a list, it will first be processed by the method
to create the list and then rendered.
When render() executes its HTML rendering, each value in the list is rendered with the corresponding widget – the first value is rendered in the first widget, the second value is rendered in the second widget, etc.
Unlike in the single value widgets, method
need not be implemented in the subclasses.
format_output
( rendered_widgets)
Given a list of rendered widgets (as strings), returns a Unicode string representing the HTML for the whole lot.
This hook allows you to format the HTML design of the widgets any way you’d like.
Here’s an example widget which subclasses
to display a date with the day, month, and year in different select boxes.
This widget is intended to be used with a
rather than a
from
datetime
import
date
from
django.forms
import
widgets
892 Chapter 6. API Reference
Django Documentation, Release 1.5.12
class DateSelectorWidget
(widgets.MultiWidget):
def __init__
( self , attrs=None):
# create choices for days, months, years
# example below, the rest snipped for brevity.
years = [(year, year) for year in ( 2011 , 2012 , 2013 )]
_widgets = ( widgets.Select(attrs=attrs, choices=days), widgets.Select(attrs=attrs, choices=months), widgets.Select(attrs=attrs, choices=years),
) super (DateSelectorWidget, self ).
__init__
(_widgets, attrs)
def decompress
( self , value):
if
value:
return
[value.day, value.month, value.year]
return
[None, None, None]
def format_output
( self , rendered_widgets):
return
u''
.
join(rendered_widgets)
def value_from_datadict
( self , data, files, name): datelist = [ widget.value_from_datadict(data, files, name + '_%s'
%
i)
try
:
for
i, widget in enumerate ( self
.
widgets)]
D = date(day= int (datelist[ 0 ]), month= int (datelist[ 1 ]), year= int (datelist[ 2 ]))
except ValueError
:
return
''
else
:
return
str (D)
The constructor creates several
widgets in a tuple. The super class uses this tuple to setup the widget.
The
method is fairly vanilla here (in fact, it’s the same as what’s been implemented as the default for MultiWidget), but the idea is that you could add custom HTML between the widgets should you wish.
The required method
breaks up a datetime.date value into the day, month, and year values corresponding to each widget. Note how the method handles the case where value is None.
The default implementation of
returns a list of values corresponding to each
Widget
. This is appropriate when using a MultiWidget with a
use this widget with a
which takes a single value, we have overridden this method to combine the data of all the subwidgets into a datetime.date. The method extracts data from the POST dictionary and constructs and validates the date. If it is valid, we return the string, otherwise, we return an empty string which will cause form.is_valid to return False.
Built-in widgets
Django provides a representation of all the basic HTML widgets, plus some commonly used groups of widgets in the django.forms.widgets
module, including
various checkboxes and selectors
and
handling of multi-valued input .
6.9. Forms 893
Django Documentation, Release 1.5.12
Widgets handling input of text
These widgets make use of the HTML elements input and textarea.
TextInput
class TextInput
Text input: <input type='text' ...>
PasswordInput
class PasswordInput
Password input: <input type='password' ...>
Takes one optional argument:
render_value
Determines whether the widget will have a value filled in when the form is re-displayed after a validation error (default is False).
HiddenInput
class HiddenInput
Hidden input: <input type='hidden' ...>
Note that there also is a
widget that encapsulates a set of hidden input elements.
DateInput
class DateInput
Date input as a simple text box: <input type='text' ...>
Takes same arguments as
, with one more optional argument:
format
The format in which this field’s initial value will be displayed.
If no format argument is provided, the default format is the first format found in
and respects
DateTimeInput
class DateTimeInput
Date/time input as a simple text box: <input type='text' ...>
Takes same arguments as
TextInput , with one more optional argument:
format
The format in which this field’s initial value will be displayed.
If no format argument is provided, the default format is the first format found in
and respects
894 Chapter 6. API Reference
Django Documentation, Release 1.5.12
TimeInput
class TimeInput
Time input as a simple text box: <input type='text' ...>
Takes same arguments as
, with one more optional argument:
format
The format in which this field’s initial value will be displayed.
If no format argument is provided, the default format is the first format found in
and respects
Textarea
class Textarea
Text area: <textarea>...</textarea>
Selector and checkbox widgets
CheckboxInput
class CheckboxInput
Checkbox: <input type='checkbox' ...>
Takes one optional argument:
check_test
A callable that takes the value of the CheckboxInput and returns True if the checkbox should be checked for that value. Exceptions from check_test used to be silenced by its caller, this is no longer the case, they will propagate upwards.
Select
class Select
Select widget: <select><option ...>...</select>
choices
This attribute is optional when the form field does not have a choices attribute. If it does, it will override anything you set here when the attribute is updated on the
NullBooleanSelect
class NullBooleanSelect
Select widget with options ‘Unknown’, ‘Yes’ and ‘No’
SelectMultiple
class SelectMultiple
Similar to
, but allows multiple selection: <select multiple='multiple'>...</select>
6.9. Forms 895
Django Documentation, Release 1.5.12
RadioSelect
class RadioSelect
Similar to
Select , but rendered as a list of radio buttons within <li> tags:
<ul>
<li><input type='radio' ...></li>
...
</ul>
For more granular control over the generated markup, you can loop over the radio buttons in the template.
Assuming a form myform with a field beatles that uses a RadioSelect as its widget:
{% for
radio
in
myform.beatles
%}
< div class
=
"myradio" >
{{
radio
}}
</ div >
{% endfor %}
This would generate the following HTML:
< div class
=
"myradio" >
< label >< input type
=
"radio" name
=
"beatles" value
=
"john" /> John</ label >
</ div >
< div class
=
"myradio" >
< label >< input type
=
"radio" name
=
"beatles" value
=
"paul" /> Paul</ label >
</ div >
< div class
=
"myradio" >
< label >< input type
=
"radio" name
=
"beatles" value
=
"george" /> George</ label >
</ div >
< div class
=
"myradio" >
< label >< input type
=
"radio" name
=
"beatles" value
=
"ringo" /> Ringo</ label >
</ div >
That included the <label> tags.
To get more granular, you can use each radio button’s tag and choice_label attributes. For example, this template...
{% for
radio
in
myform.beatles
%}
< label >
{{
radio.choice_label
}}
< span class
=
"radio" >
{{
radio.tag
}}
</ span >
</ label >
{% endfor %}
...will result in the following HTML:
< label >
John
< span class
=
"radio" >< input type
=
"radio" name
=
"beatles" value
=
"john" /></ span >
</ label >
< label >
Paul
< span class
=
"radio" >< input type
=
"radio" name
=
"beatles" value
=
"paul" /></ span >
</ label >
< label >
George
< span class
=
"radio" >< input type
=
"radio" name
=
"beatles" value
=
"george" /></
˓→ span >
896 Chapter 6. API Reference
Django Documentation, Release 1.5.12
</ label >
< label >
Ringo
< span class
=
"radio" >< input type
=
"radio" name
=
"beatles" value
=
"ringo" /></ span >
</ label >
If you decide not to loop over the radio buttons – e.g., if your template simply includes {{ myform.beatles
}}
– they’ll be output in a <ul> with <li> tags, as above.
CheckboxSelectMultiple
class CheckboxSelectMultiple
Similar to
, but rendered as a list of check buttons:
<ul>
<li><input type='checkbox' ...></li>
...
</ul>
File upload widgets
FileInput
class FileInput
File upload input: <input type='file' ...>
ClearableFileInput
class ClearableFileInput
File upload input: <input type='file' ...>, with an additional checkbox input to clear the field’s value, if the field is not required and has initial data.
Composite widgets
MultipleHiddenInput
class MultipleHiddenInput
Multiple <input type='hidden' ...> widgets.
A widget that handles multiple hidden widgets for fields that have a list of values.
choices
This attribute is optional when the form field does not have a choices attribute. If it does, it will override anything you set here when the attribute is updated on the
SplitDateTimeWidget
class SplitDateTimeWidget
Wrapper (using
for the date, and
for the time.
6.9. Forms 897
Django Documentation, Release 1.5.12
SplitDateTimeWidget has two optional attributes:
date_format
Similar to
time_format
Similar to
SplitHiddenDateTimeWidget
class SplitHiddenDateTimeWidget
Similar to
for both date and time.
SelectDateWidget
class SelectDateWidget
Wrapper around three
widgets: one each for month, day, and year. Note that this widget lives in a separate file from the standard widgets.
Takes one optional argument:
years
An optional list/tuple of years to use in the “year” select box. The default is a list containing the current year and the next 9 years.
Form and field validation
Form validation happens when the data is cleaned. If you want to customize this process, there are various places you can change, each one serving a different purpose. Three types of cleaning methods are run during form processing.
These are normally executed when you call the is_valid() method on a form. There are other things that can trigger cleaning and validation (accessing the errors attribute or calling full_clean() directly), but normally they won’t be needed.
In general, any cleaning method can raise ValidationError if there is a problem with the data it is processing, passing the relevant error message to the ValidationError constructor. If no ValidationError is raised, the method should return the cleaned (normalized) data as a Python object.
If you detect multiple errors during a cleaning method and wish to signal all of them to the form submitter, it is possible to pass a list of errors to the ValidationError constructor.
Most validation can be done using
- simple helpers that can be reused easily. Validators are simple functions
(or callables) that take a single argument and raise ValidationError on invalid input. Validators are run after the field’s to_python and validate methods have been called.
Validation of a Form is split into several steps, which can be customized or overridden:
• The to_python() method on a Field is the first step in every validation. It coerces the value to correct datatype and raises ValidationError if that is not possible. This method accepts the raw value from the widget and returns the converted value. For example, a FloatField will turn the data into a Python float or raise a ValidationError.
• The validate() method on a Field handles field-specific validation that is not suitable for a validator, It takes a value that has been coerced to correct datatype and raises ValidationError on any error. This method does not return anything and shouldn’t alter the value. You should override it to handle validation logic that you can’t or don’t want to put in a validator.
898 Chapter 6. API Reference
Django Documentation, Release 1.5.12
• The run_validators() method on a Field runs all of the field’s validators and aggregates all the errors into a single ValidationError. You shouldn’t need to override this method.
• The clean() method on a Field subclass. This is responsible for running to_python, validate and run_validators in the correct order and propagating their errors. If, at any time, any of the methods raise
ValidationError , the validation stops and that error is raised. This method returns the clean data, which is then inserted into the cleaned_data dictionary of the form.
• The clean_<fieldname>() method in a form subclass – where <fieldname> is replaced with the name of the form field attribute. This method does any cleaning that is specific to that particular attribute, unrelated to the type of field that it is. This method is not passed any parameters. You will need to look up the value of the field in self.cleaned_data and remember that it will be a Python object at this point, not the original string submitted in the form (it will be in cleaned_data because the general field clean() method, above, has already cleaned the data once).
For example, if you wanted to validate that the contents of a CharField called serialnumber was unique, clean_serialnumber() would be the right place to do this. You don’t need a specific field (it’s just a
CharField
), but you want a formfield-specific piece of validation and, possibly, cleaning/normalizing the data.
This method should return the cleaned value obtained from cleaned_data, regardless of whether it changed anything or not.
• The Form subclass’s clean() method. This method can perform any validation that requires access to multiple fields from the form at once. This is where you might put in things to check that if field A is supplied, field B must contain a valid email address and the like. The data that this method returns is the final cleaned_data attribute for the form, so don’t forget to return the full list of cleaned data if you override this method (by default,
Form.clean() just returns self.cleaned_data).
Since the field validation method have been run by the time clean() is called, you also have access to the form’s errors attribute which contains all the errors raised by previous steps.
Note that any errors raised by your Form.clean() override will not be associated with any field in particular.
They go into a special “field” (called __all__), which you can access via the non_field_errors() method if you need to. If you want to attach errors to a specific field in the form, you will need to access the
_errors attribute on the form, which is
Also note that there are special considerations when overriding the clean() method of a ModelForm subclass. (see the
for more information)
These methods are run in the order given above, one field at a time.
That is, for each field in the form (in the order they are declared in the form definition), the Field.clean() method (or its override) is run, then clean_<fieldname>()
. Finally, once those two methods are run for every field, the Form.clean() method, or its override, is executed, no matter if the previous methods have raised errors or not.
Examples of each of these methods are provided below.
As mentioned, any of these methods can raise a ValidationError. For any field, if the Field.clean() method raises a ValidationError, any field-specific cleaning method is not called. However, the cleaning methods for all remaining fields are still executed.
Form subclasses and modifying field errors
Sometimes, in a form’s clean() method, you will want to add an error message to a particular field in the form. This won’t always be appropriate and the more typical situation is to raise a ValidationError from Form.clean(), which is turned into a form-wide error that is available through the Form.non_field_errors() method.
When you really do need to attach the error to a particular field, you should store (or amend) a key in the Form.
_errors attribute. This attribute is an instance of a django.forms.util.ErrorDict class. Essentially,
6.9. Forms 899
Django Documentation, Release 1.5.12
though, it’s just a dictionary. There is a key in the dictionary for each field in the form that has an error. Each value in the dictionary is a django.forms.util.ErrorList instance, which is a list that knows how to display itself in different ways. So you can treat _errors as a dictionary mapping field names to lists.
If you want to add a new error to a particular field, you should check whether the key already exists in self.
_errors or not. If not, create a new entry for the given key, holding an empty ErrorList instance. In either case, you can then append your error message to the list for the field name in question and it will be displayed when the form is displayed.
There is an example of modifying self._errors in the following section.
What’s in a name?
You may be wondering why is this attribute called _errors and not errors. Normal Python practice is to prefix a name with an underscore if it’s not for external usage. In this case, you are subclassing the Form class, so you are essentially writing new internals. In effect, you are given permission to access some of the internals of Form.
Of course, any code outside your form should never access _errors directly. The data is available to external code through the errors property, which populates _errors before returning it).
Another reason is purely historical: the attribute has been called _errors since the early days of the forms module and changing it now (particularly since errors is used for the read-only property name) would be inconvenient for a number of reasons. You can use whichever explanation makes you feel more comfortable. The result is the same.
Using validation in practice
The previous sections explained how validation works in general for forms. Since it can sometimes be easier to put things into place by seeing each feature in use, here are a series of small examples that use each of the previous features.
Using validators
Django’s form (and model) fields support use of simple utility functions and classes known as validators. A validator is merely a callable object or function that takes a value and simply returns nothing if the value is valid or raises a
if not. These can be passed to a field’s constructor, via the field’s validators argument, or defined on the
class itself with the default_validators attribute.
Simple validators can be used to validate values inside the field, let’s have a look at Django’s EmailField:
class EmailField
(CharField): default_error_messages = {
'invalid' : _( 'Enter a valid email address.' ),
} default_validators = [validators.validate_email]
As you can see, EmailField is just a CharField with customized error message and a validator that validates email addresses. This can also be done on field definition so: email = forms.EmailField() is equivalent to: email = forms.CharField(validators=[validators.validate_email], error_messages={ 'invalid' : _( 'Enter a valid email address.' )})
900 Chapter 6. API Reference
Django Documentation, Release 1.5.12
Common cases such as validating against an email or a regular expression can be handled using existing validator classes available in Django. For example, validators.validate_slug is an instance of a
constructed with the first argument being the pattern: ^[-a-zA-Z0-9_]+$. See the section on
to see a list of what is already available and for an example of how to write a validator.
Form field default cleaning
Let’s firstly create a custom form field that validates its input is a string containing comma-separated email addresses.
The full class looks like this:
from
django
import
forms
from
django.core.validators
import
validate_email
class MultiEmailField
(forms.Field):
def to_python
( self , value):
"Normalize data to a list of strings."
# Return an empty list if no input was given.
if not
value:
return
[]
return
value.split( ',' )
def validate
( self , value):
"Check if value consists only of valid emails."
# Use the parent's handling of required fields, etc.
super (MultiEmailField, self ).validate(value)
for
email in value: validate_email(email)
Every form that uses this field will have these methods run before anything else can be done with the field’s data. This is cleaning that is specific to this type of field, regardless of how it is subsequently used.
Let’s create a simple ContactForm to demonstrate how you’d use this field:
class ContactForm
(forms.Form): subject = forms.CharField(max_length= 100 ) message = forms.CharField() sender = forms.EmailField() recipients = MultiEmailField() cc_myself = forms.BooleanField(required=False)
Simply use MultiEmailField like any other form field. When the is_valid() method is called on the form, the MultiEmailField.clean() method will be run as part of the cleaning process and it will, in turn, call the custom to_python() and validate() methods.
Cleaning a specific field attribute
Continuing on from the previous example, suppose that in our ContactForm, we want to make sure that the recipients field always contains the address "[email protected]". This is validation that is specific to our form, so we don’t want to put it into the general MultiEmailField class. Instead, we write a cleaning method that operates on the recipients field, like so:
6.9. Forms 901
Django Documentation, Release 1.5.12
class ContactForm
(forms.Form):
# Everything as before.
...
def clean_recipients
( self ): data = self
.
cleaned_data[ 'recipients' ]
if
not in
data:
raise
forms.ValidationError( "You have forgotten about Fred!" )
# Always return the cleaned data, whether you have changed it or
# not.
return
data
Cleaning and validating fields that depend on each other
django.forms.Form.clean()
Suppose we add another requirement to our contact form: if the cc_myself field is True, the subject must contain the word "help". We are performing validation on more than one field at a time, so the form’s clean() method is a good spot to do this. Notice that we are talking about the clean() method on the form here, whereas earlier we were writing a clean() method on a field. It’s important to keep the field and form difference clear when working out where to validate things. Fields are single data points, forms are a collection of fields.
By the time the form’s clean() method is called, all the individual field clean methods will have been run (the previous two sections), so self.cleaned_data will be populated with any data that has survived so far. So you also need to remember to allow for the fact that the fields you are wanting to validate might not have survived the initial individual field checks.
There are two ways to report any errors from this step. Probably the most common method is to display the error at the top of the form. To create such an error, you can raise a ValidationError from the clean() method. For example:
class ContactForm
(forms.Form):
# Everything as before.
...
def clean
( self ): cleaned_data = super (ContactForm, self ).clean() cc_myself = cleaned_data.get( "cc_myself" ) subject = cleaned_data.get( "subject" )
if
cc_myself and subject:
# Only do something if both fields are valid so far.
if
"help"
not in
subject:
raise
forms.ValidationError( "Did not send for 'help' in "
"the subject despite CC'ing yourself." )
# Always return the full collection of cleaned data.
return
cleaned_data
In this code, if the validation error is raised, the form will display an error message at the top of the form (normally) describing the problem.
Note that the call to super(ContactForm, self).clean() in the example code ensures that any validation logic in parent classes is maintained.
The second approach might involve assigning the error message to one of the fields. In this case, let’s assign an error
902 Chapter 6. API Reference
Download
Advertisement
Key features
Free and open-source
Written in Python
Rapid development
Reusability and pluggability
Clean and pragmatic design
Active community
Frequently asked questions
Django is a Python-based web framework designed to simplify the development of complex, database-driven websites.
Django offers features like rapid development, reusability, pluggability, clean design, and a strong community.
Django helps you build websites efficiently, with a focus on security and scalability.