Django Documentation, Release 1.11.8.dev20171115160334
FileUploadHandler.chunk_size
Size, in bytes, of the “chunks” Django should store into memory and feed into the handler. That is, this attribute controls the size of chunks fed into FileUploadHandler.receive_data_chunk.
For maximum performance the chunk sizes should be divisible by 4 and should not exceed 2 GB (2
31 bytes) in size. When there are multiple chunk sizes provided by multiple handlers, Django will use the smallest chunk size defined by any handler.
The default is 64*2 10 bytes, or 64 KB.
FileUploadHandler.new_file( field_name , file_name, content_type, content_length, charset, content_type_extra)
Callback signaling that a new file upload is starting. This is called before any data has been fed to any upload handlers.
field_name is a string name of the file <input> field.
file_name is the unicode filename that was provided by the browser.
content_type is the MIME type provided by the browser – E.g. 'image/jpeg'.
content_length is the length of the image given by the browser. Sometimes this won’t be provided and will be None.
charset is the character set (i.e. utf8) given by the browser. Like content_length, this sometimes won’t be provided.
content_type_extra is extra information about the file from the content-type header.
See
UploadedFile.content_type_extra
.
This method may raise a StopFutureHandlers exception to prevent future handlers from handling this file.
FileUploadHandler.upload_complete()
Callback signaling that the entire upload (all files) has completed.
FileUploadHandler.handle_raw_input( input_data , META, content_length, boundary, encoding)
Allows the handler to completely override the parsing of the raw HTTP input.
input_data is a file-like object that supports read()-ing.
META is the same object as request.META.
content_length is the length of the data in input_data. Don’t read more than content_length bytes from input_data.
boundary is the MIME boundary for this request.
encoding is the encoding of the request.
Return None if you want upload handling to continue, or a tuple of (POST, FILES) if you want to return the new data structures suitable for the request directly.
6.12 Forms
Detailed form API reference. For introductory material, see the
Working with forms
topic guide.
6.12.1 The Forms API
About this document
6.12. Forms 1031
Django Documentation, Release 1.11.8.dev20171115160334
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
Form
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
Form
instance, simply instantiate the class:
>>> f = ContactForm()
To bind data to a form, pass the data as a dictionary as the first parameter to your
Form
class constructor:
>>> data = { 'subject' : 'hello' ,
...
...
'message'
'sender' :
: 'Hi there' ,
'[email protected]' ,
...
'cc_myself' : True}
>>> f = ContactForm(data)
In this dictionary, the keys are the field names, which correspond to the attributes in your
Form
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
Field , as we’ll see in a moment.
Form.is_bound
If you need to distinguish between bound and unbound form instances at runtime, check the value of the form’s
is_bound
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
Form
instance and want to change the data somehow, or if you want to bind an unbound
Form
instance to some data, create another
Form
instance. There is no way to change data in a
Form
instance. Once a
Form
instance has been created, you should consider its data immutable, whether it has data or not.
Using forms to validate data
Form.clean()
1032 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
Implement a clean() method on your Form when you must add custom validation for fields that are interdependent.
See
Cleaning and validating fields that depend on each other
for example usage.
Form.is_valid()
The primary task of a
Form
object is to validate data. With a bound
Form
instance, call the
is_valid()
method to run validation and return a boolean designating whether the data was valid:
>>> data = { 'subject' : 'hello' ,
...
...
'message'
'sender' :
: 'Hi there' ,
'[email protected]' ,
...
'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'
'cc_myself' : True}
,
>>> f = ContactForm(data)
>>> f.is_valid()
False
Form.errors
Access the
errors
attribute to get a dictionary of error messages:
>>> f.errors
{'sender': ['Enter a valid email address.'], 'subject': ['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
errors
without having to call
is_valid()
first. The form’s data will be validated the first time either you call
is_valid()
or access
errors .
The validation routines will only get called once, regardless of how many times you access
errors
or call
is_valid() . This means that if validation has side effects, those side effects will only be triggered once.
Form.errors.as_data()
Returns a dict that maps fields to their original ValidationError instances.
>>> f.errors.as_data()
{'sender': [ValidationError(['Enter a valid email address.'])],
'subject': [ValidationError(['This field is required.'])]}
Use this method anytime you need to identify an error by its code. This enables things like rewriting the error’s message or writing custom logic in a view when a given error is present. It can also be used to serialize the errors in a custom format (e.g. XML); for instance,
as_json()
relies on as_data().
The need for the as_data() method is due to backwards compatibility. Previously ValidationError instances were lost as soon as their rendered error messages were added to the Form.errors dictionary. Ideally Form.
errors would have stored ValidationError instances and methods with an as_ prefix could render them, but it had to be done the other way around in order not to break code that expects rendered error messages in Form.
errors .
6.12. Forms 1033
Django Documentation, Release 1.11.8.dev20171115160334
Form.errors.as_json( escape_html=False)
Returns the errors serialized as JSON.
>>> f.errors.as_json()
{"sender": [{"message": "Enter a valid email address.", "code": "invalid"}],
"subject": [{"message": "This field is required.", "code": "required"}]}
By default, as_json() does not escape its output. If you are using it for something like AJAX requests to a form view where the client interprets the response and inserts errors into the page, you’ll want to be sure to escape the results on the client-side to avoid the possibility of a cross-site scripting attack. It’s trivial to do so using a JavaScript library like jQuery - simply use $(el).text(errorText) rather than .html().
If for some reason you don’t want to use client-side escaping, you can also set escape_html=True and error messages will be escaped so you can use them directly in HTML.
Form.add_error( field , error)
This method allows adding errors to specific fields from within the Form.clean() method, or from outside the form altogether; for instance from a view.
The field argument is the name of the field to which the errors should be added. If its value is None the error will be treated as a non-field error as returned by
Form.non_field_errors() .
The error argument can be a simple string, or preferably an instance of ValidationError. See
Raising ValidationError
for best practices when defining form errors.
Note that Form.add_error() automatically removes the relevant field from cleaned_data.
Form.has_error( field , code=None)
This method returns a boolean designating whether a field has an error with a specific error code. If code is None, it will return True if the field contains any errors at all.
To check for non-field errors use
NON_FIELD_ERRORS
as the field parameter.
Form.non_field_errors()
This method returns the list of errors from
Form.errors
that aren’t associated with a particular field. This includes
ValidationError s that are raised in
Form.clean()
and errors added using
Form.add_error(None, ".
..") .
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
initial
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.
1034 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
To accomplish this, use the
initial
argument to a
Form . 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.
If a
Field
defines
initial
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:
>>> from django import forms
>>> class CommentForm (forms.Form):
...
name = forms.CharField(initial= 'class' )
...
url = forms.URLField()
...
comment = forms.CharField()
>>> f = CommentForm(initial={ 'name' : 'instance' }, auto_id=False)
>>> print (f)
<tr><th>Name:</th><td><input type="text" name="name" value="instance" required /></td>
˓→
</tr>
<tr><th>Url:</th><td><input type="url" name="url" required /></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" required /></td></tr>
Form.get_initial_for_field( field , field_name)
Use
get_initial_for_field()
to retrieve initial data for a form field. It retrieves data from
Form.initial
and
Field.initial
, in that order, and evaluates any callable initial values.
Checking which form data has changed
Form.has_changed()
Use the has_changed() method on your Form when you need to check if the form data has been changed from the initial data.
>>> data = { 'subject' : 'hello' ,
...
...
'message'
'sender' :
: 'Hi there' ,
'[email protected]' ,
...
'cc_myself' : True}
>>> f = ContactForm(data, initial=data)
>>> f.has_changed()
False
When the form is submitted, we reconstruct it and provide the original data so that the comparison can be done:
>>> f = ContactForm(request.POST, initial=data)
>>> f.has_changed() has_changed() will be True if the data from request.POST differs from what was provided in
initial
or
False otherwise. The result is computed by calling
Field.has_changed()
for each field in the form.
Form.changed_data
The changed_data attribute returns a list of the names of the fields whose values in the form’s bound data (usually request.POST
) differ from what was provided in
initial . It returns an empty list if no data differs.
6.12. Forms 1035
Django Documentation, Release 1.11.8.dev20171115160334
>>> f = ContactForm(request.POST, initial=data)
>>> if f.has_changed():
...
print ( "The following fields changed: %s" % ", " .
join(f.changed_data))
Accessing the fields from the form
Form.fields
You can access the fields of
Form
instance from its fields attribute:
>>> for row in f.fields.values(): print (row)
...
<django.forms.fields.CharField object at 0x7ffaac632510>
<django.forms.fields.URLField object at 0x7ffaac632f90>
<django.forms.fields.CharField object at 0x7ffaac3aa050>
>>> f.fields[ 'name' ]
<django.forms.fields.CharField object at 0x7ffaac6324d0>
You can alter the field of
Form
instance to change the way it is presented in the form:
>>> f.as_table().split( '\n' )[ 0 ]
'<tr><th>Name:</th><td><input name="name" type="text" value="instance" required /></
˓→ td></tr>'
>>> f.fields[ 'name' ].label = "Username"
>>> f.as_table().split( '\n' )[ 0 ]
'<tr><th>Username:</th><td><input name="name" type="text" value="instance" required />
˓→
</td></tr>'
Beware not to alter the base_fields attribute because this modification will influence all subsequent
ContactForm instances within the same Python process:
>>> f.base_fields[ 'name' ].label = "Username"
>>> another_f = CommentForm(auto_id=False)
>>> another_f.as_table().split( '\n' )[ 0 ]
'<tr><th>Username:</th><td><input name="name" type="text" value="class" required /></
˓→ td></tr>'
Accessing “clean” data
Form.cleaned_data
Each field in a
Form
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,
DateField
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
Form
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' :
:
'cc_myself'
'Hi there'
: True}
,
'[email protected]' ,
1036 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
>>> f = ContactForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data
{'cc_myself': True, 'message': 'Hi there', 'sender': '[email protected]', 'subject':
˓→
'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'
'sender' :
:
'cc_myself'
'Hi there'
: True}
,
'invalid email address' ,
>>> f = ContactForm(data)
>>> f.is_valid()
False
>>> f.cleaned_data
{'cc_myself': True, 'message': 'Hi there'} 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' ,
'[email protected]' ,
...
...
...
...
'cc_myself' : True,
'extra_field_1'
'extra_field_2'
'extra_field_3'
>>> f = ContactForm(data)
>>> f.is_valid()
True
:
:
:
'foo'
'bar'
'baz'
,
,
}
>>> f.cleaned_data # Doesn't contain extra_field_1, etc.
{'cc_myself': True, 'message': 'Hi there', 'sender': '[email protected]', 'subject':
˓→
'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:
>>> from django import forms
>>> class OptionalPersonForm (forms.Form):
...
first_name = forms.CharField()
...
...
last_name = forms.CharField() nick_name = forms.CharField(required=False)
>>> data = { 'first_name' : 'John' , 'last_name' : 'Lennon' }
>>> f = OptionalPersonForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data
{'nick_name': '', 'first_name': 'John', 'last_name': '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
6.12. Forms 1037
Django Documentation, Release 1.11.8.dev20171115160334
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
Form and field validation .
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" required /></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name=
˓→
"message" id="id_message" required /></td></tr>
<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name=
˓→
"sender" id="id_sender" required /></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 if appropriate:
>>> data = { 'subject' : 'hello' ,
...
...
'message'
'sender' :
: 'Hi there' ,
'[email protected]' ,
...
'cc_myself' : True}
>>> f = ContactForm(data)
>>> print (f)
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type=
˓→
"text" name="subject" maxlength="100" value="hello" required /></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name=
˓→
"message" id="id_message" value="Hi there" required /></td></tr>
<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name=
˓→
"sender" id="id_sender" value="[email protected]" required /></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 /></td></tr>
The checked attribute was changed to use HTML5 boolean syntax rather than checked="checked".
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 is represented by an <input type="text"> and EmailField by an <input type="email">. 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.
1038 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
• 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.
• The output uses HTML5 syntax, targeting <!DOCTYPE html>. For example, it uses boolean attributes such as checked rather than the XHTML style of checked='checked'.
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()
'<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name=
˓→
"subject" maxlength="100" required /></p>\n<p><label for="id_message">Message:</
˓→ label> <input type="text" name="message" id="id_message" required /></p>\n<p><label
˓→ for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender"
˓→ required /></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" required /></p>
<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_
˓→ message" required /></p>
<p><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_
˓→ sender" required /></p>
<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself
˓→
" id="id_cc_myself" /></p> 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()
'<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name=
˓→
"subject" maxlength="100" required /></li>\n<li><label for="id_message">Message:</
˓→ label> <input type="text" name="message" id="id_message" required /></li>\n<li>
˓→
<label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_
˓→ sender" required /></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" required /></li>
<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_
˓→ message" required /></li>
<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_
˓→ sender" required /></li>
<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_
˓→ myself" id="id_cc_myself" /></li>
6.12. Forms 1039
Django Documentation, Release 1.11.8.dev20171115160334
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()
'<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type=
˓→
"text" name="subject" maxlength="100" required /></td></tr>\n<tr><th><label for="id_
˓→ message">Message:</label></th><td><input type="text" name="message" id="id_message"
˓→ required /></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td>
˓→
<input type="email" name="sender" id="id_sender" required /></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)
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type=
˓→
"text" name="subject" maxlength="100" required /></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name=
˓→
"message" id="id_message" required /></td></tr>
<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name=
˓→
"sender" id="id_sender" required /></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
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
Form
class has a couple of hooks you can use to add class attributes to required rows or to rows with errors: simply set the
Form.error_css_class
and/or
Form.required_css_class
attributes: from django import forms class ContactForm (forms.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 class="required" for="id_subject">Subject:</label>
˓→
...
<tr class="required"><th><label class="required" for="id_message">Message:</label>
˓→
...
1040 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
<tr class="required error"><th><label class="required" for="id_sender">Sender:</label>
˓→
...
<tr><th><label for="id_cc_myself">Cc myself:<label> ...
>>> f[ 'subject' ].label_tag()
<label class="required" for="id_subject">Subject:</label>
>>> f[ 'subject' ].label_tag(attrs={ 'class' : 'foo' })
<label for="id_subject" class="foo required">Subject:</label>
Configuring form elements’ HTML id attributes and <label> tags
Form.auto_id
By default, the form rendering methods include:
• HTML id attributes on the form elements.
• The corresponding <label> tags around the labels. 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.
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 id and label 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" required />
˓→
</td></tr>
<tr><th>Message:</th><td><input type="text" name="message" required /></td></tr>
<tr><th>Sender:</th><td><input type="email" name="sender" required /></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" required /></li>
<li>Message: <input type="text" name="message" required /></li>
<li>Sender: <input type="email" name="sender" required /></li>
<li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
>>> print (f.as_p())
<p>Subject: <input type="text" name="subject" maxlength="100" required /></p>
<p>Message: <input type="text" name="message" required /></p>
<p>Sender: <input type="email" name="sender" required /></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:
>>> 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" required /></td></tr>
<tr><th><label for="message">Message:</label></th><td><input type="text" name="message
˓→
" id="message" required /></td></tr>
<tr><th><label for="sender">Sender:</label></th><td><input type="email" name="sender"
˓→ id="sender" required /></td></tr>
<tr><th><label for="cc_myself">Cc myself:</label></th><td><input type="checkbox" name=
˓→
"cc_myself" id="cc_myself" /></td></tr>
6.12. Forms 1041
Django Documentation, Release 1.11.8.dev20171115160334
>>> print (f.as_ul())
<li><label for="subject">Subject:</label> <input id="subject" type="text" name=
˓→
"subject" maxlength="100" required /></li>
<li><label for="message">Message:</label> <input type="text" name="message" id=
˓→
"message" required /></li>
<li><label for="sender">Sender:</label> <input type="email" name="sender" id="sender"
˓→ required /></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" required /></p>
<p><label for="message">Message:</label> <input type="text" name="message" id="message
˓→
" required /></p>
<p><label for="sender">Sender:</label> <input type="email" name="sender" id="sender"
˓→ required /></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" required /></td></tr>
<tr><th><label for="id_for_message">Message:</label></th><td><input type="text" name=
˓→
"message" id="id_for_message" required /></td></tr>
<tr><th><label for="id_for_sender">Sender:</label></th><td><input type="email" name=
˓→
"sender" id="id_for_sender" required /></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" required /></li>
<li><label for="id_for_message">Message:</label> <input type="text" name="message" id=
˓→
"id_for_message" required /></li>
<li><label for="id_for_sender">Sender:</label> <input type="email" name="sender" id=
˓→
"id_for_sender" required /></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" required /></p>
<p><label for="id_for_message">Message:</label> <input type="text" name="message" id=
˓→
"id_for_message" required /></p>
<p><label for="id_for_sender">Sender:</label> <input type="email" name="sender" id=
˓→
"id_for_sender" required /></p>
<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'.
Form.label_suffix
1042 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
A translatable string (defaults to a colon (:) in English) that will be appended after any label name when a form is rendered.
It’s possible to customize that 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" required /></li>
<li><label for="id_for_message">Message</label> <input type="text" name="message" id=
˓→
"id_for_message" required /></li>
<li><label for="id_for_sender">Sender</label> <input type="email" name="sender" id=
˓→
"id_for_sender" required /></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" required /></li>
<li><label for="id_for_message">Message -></label> <input type="text" name="message"
˓→ id="id_for_message" required /></li>
<li><label for="id_for_sender">Sender -></label> <input type="email" name="sender" id=
˓→
"id_for_sender" required /></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 (in English, those are ., !, ? or :).
Fields can also define their own
label_suffix . This will take precedence over
Form.label_suffix
. The
suffix can also be overridden at runtime using the label_suffix parameter to
label_tag() .
Form.use_required_attribute
When set to True (the default), required form fields will have the required HTML attribute.
Formsets
instantiate forms with use_required_attribute=False to avoid incorrect browser validation when adding and deleting forms from a formset.
Configuring the rendering of a form’s widgets
Form.default_renderer
Specifies the
renderer
to use for the form. Defaults to None which means to use the default renderer specified by the
FORM_RENDERER
setting.
You can set this as a class attribute when declaring your form or use the renderer argument to Form.
__init__() . For example: from django import forms class MyForm (forms.Form): default_renderer = MyRenderer() or: form = MyForm(renderer=MyRenderer())
6.12. Forms 1043
Django Documentation, Release 1.11.8.dev20171115160334
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.
There are several other ways to customize the order:
Form.field_order
By default Form.field_order=None, which retains the order in which you define the fields in your form class. If field_order is a list of field names, the fields are ordered as specified by the list and remaining fields are appended according to the default order. Unknown field names in the list are ignored. This makes it possible to disable a field in a subclass by setting it to None without having to redefine ordering.
You can also use the Form.field_order argument to a
Form
to override the field order. If a
Form
defines
field_order
and you include field_order when instantiating the Form, then the latter field_order will have precedence.
Form.order_fields( field_order)
You may rearrange the fields any time using order_fields() with a list of field names as in
field_order .
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' : 'Hi there' ,
...
...
'sender' : '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" required /></td></tr>
<tr><th>Message:</th><td><input type="text" name="message" value="Hi there" required /
˓→
></td></tr>
<tr><th>Sender:</th><td><ul class="errorlist"><li>Enter a valid email address.</li></
˓→ ul><input type="email" name="sender" value="invalid email address" required /></td>
˓→
</tr>
<tr><th>Cc myself:</th><td><input 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" required /></li>
<li>Message: <input type="text" name="message" value="Hi there" required /></li>
<li><ul class="errorlist"><li>Enter a valid email address.</li></ul>Sender: <input
˓→ type="email" name="sender" value="invalid email address" required /></li>
<li>Cc myself: <input 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" required /></p>
<p>Message: <input type="text" name="message" value="Hi there" required /></p>
<p><ul class="errorlist"><li>Enter a valid email address.</li></ul></p>
1044 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
<p>Sender: <input type="email" name="sender" value="invalid email address" required />
˓→
</p>
<p>Cc myself: <input checked type="checkbox" name="cc_myself" /></p>
Customizing the error list format
By default, forms use django.forms.utils.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 (replace __str__ by __unicode__ on Python 2):
>>> from django.forms.utils
import ErrorList
>>> class DivErrorList (ErrorList):
...
def __str__ ( self ): # __unicode__ on Python 2
...
...
...
...
def return as_divs if not return self
( self
.
self as_divs()
):
: return ''
'<div class="errorlist">%s</div>' % '' .
join([ '<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" required /></p>
<p>Message: <input type="text" name="message" value="Hi there" required /></p>
<div class="errorlist"><div class="error">Enter a valid email address.</div></div>
<p>Sender: <input type="email" name="sender" value="invalid email address" required />
˓→
</p>
<p>Cc myself: <input checked type="checkbox" name="cc_myself" /></p>
More granular output
The as_p(), as_ul(), and as_table() methods are simply shortcuts – 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
Form
instance.
The __str__() (__unicode__ on Python 2) method 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:
>>> form = ContactForm()
>>> print (form[ 'subject' ])
<input id="id_subject" type="text" name="subject" maxlength="100" required />
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" required />
<input type="text" name="message" id="id_message" required />
<input type="email" name="sender" id="id_sender" required />
<input type="checkbox" name="cc_myself" id="id_cc_myself" />
The field-specific output honors the form object’s auto_id setting:
6.12. Forms 1045
Django Documentation, Release 1.11.8.dev20171115160334
>>> f = ContactForm(auto_id=False)
>>> print (f[ 'message' ])
<input type="text" name="message" required />
>>> f = ContactForm(auto_id= 'id_%s' )
>>> print (f[ 'message' ])
<input type="text" name="message" id="id_message" required />
Attributes of BoundField
BoundField.auto_id
The HTML ID attribute for this BoundField. Returns an empty string if
Form.auto_id
is False.
BoundField.data
This property returns the data for this
BoundField
extracted by the widget’s
value_from_datadict()
method, or None if it wasn’t given:
>>> unbound_form = ContactForm()
>>> print (unbound_form[ 'subject' ].data)
None
>>> bound_form = ContactForm(data={ 'subject' : 'My Subject' })
>>> print (bound_form[ 'subject' ].data)
My Subject
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" required />
>>> f[ 'message' ].errors
['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.field
The form
Field
instance from the form class that this
BoundField
wraps.
BoundField.form
The
Form
instance this
BoundField
is bound to.
BoundField.help_text
The
help_text
of the field.
BoundField.html_name
The name that will be used in the widget’s HTML name attribute. It takes the form
prefix
into account.
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
label_tag()
will do this for you):
1046 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
< 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
attrs
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"
˓→ required />
BoundField.is_hidden
Returns True if this
BoundField ‘s widget is hidden.
BoundField.label
The
label
of the field. This is used in
label_tag() .
BoundField.name
The name of this field in the form:
>>> f = ContactForm()
>>> print (f[ 'subject' ].name) subject
>>> print (f[ 'message' ].name) message
Methods of BoundField
BoundField.as_hidden( attrs=None , **kwargs)
Returns a string of HTML for representing this as an <input type="hidden">.
**kwargs are passed to
as_widget() .
This method is primarily used internally. You should use a widget instead.
BoundField.as_widget( widget=None , attrs=None, only_initial=False)
Renders the field by rendering the passed widget, adding any HTML attributes passed as attrs. If no widget is specified, then the field’s default widget will be used.
only_initial is used by Django internals and should not be set explicitly.
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:
>>> f = ContactForm(data={ 'message' : '' })
>>> 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={ 'message' : '' })
>>> f[ 'message' ].css_classes( 'foo bar' )
'foo bar required'
6.12. Forms 1047
Django Documentation, Release 1.11.8.dev20171115160334
BoundField.label_tag( contents=None , attrs=None, label_suffix=None)
To separately render the label tag of a form field, you can call its label_tag() method:
>>> f = ContactForm(data={ 'message' : '' })
>>> print (f[ 'message' ].label_tag())
<label for="id_message">Message:</label>
You can provide the contents parameter which will replace the auto-generated label tag. An attrs dictionary may contain additional attributes for the <label> tag.
The HTML that’s generated includes the form’s
label_suffix
(a colon, by default) or, if set, the current field’s
label_suffix . The optional label_suffix parameter allows you to override any previously set
suffix. For example, you can use an empty string to hide the label on selected fields. If you need to do this in a template, you could write a custom filter to allow passing parameters to label_tag.
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={ 'subject' : 'hi' }, initial=initial)
>>> print (unbound_form[ 'subject' ].value()) welcome
>>> print (bound_form[ 'subject' ].value()) hi
Customizing BoundField
If you need to access some additional information about a form field in a template and using a subclass of
Field
isn’t sufficient, consider also customizing
BoundField .
A custom form field can override get_bound_field():
Field.get_bound_field( form , field_name)
Takes an instance of
Form
and the name of the field. The return value will be used when accessing the field in a template. Most likely it will be an instance of a subclass of
BoundField .
If you have a GPSCoordinatesField, for example, and want to be able to access additional information about the coordinates in a template, this could be implemented as follows: class GPSCoordinatesBoundField (BoundField):
@property def country ( self ):
"""
Return the country the coordinates lie in or None if it can't be determined.
""" value = self .
value() if value: return get_country_from_coordinates(value) else : return None class GPSCoordinatesField (Field): def get_bound_field ( self , form, field_name): return GPSCoordinatesBoundField(form, self , field_name)
Now you can access the country in a template with {{ form.coordinates.country }}.
1048 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
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' ,
...
'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 an 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>
6.12. Forms 1049
Django Documentation, Release 1.11.8.dev20171115160334
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" required /></li>
<li>Message: <input type="text" name="message" required /></li>
<li>Sender: <input type="email" name="sender" required /></li>
<li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
<li>Priority: <input type="text" name="priority" required /></li>
It’s possible to subclass multiple forms, treating forms as mixins. In this example, BeatleForm subclasses both
PersonForm and InstrumentForm (in that order), and its field list includes the fields from the parent classes:
>>> from django import forms
>>> class PersonForm (forms.Form):
...
first_name = forms.CharField()
...
last_name = forms.CharField()
>>> class InstrumentForm (forms.Form):
...
instrument = forms.CharField()
>>> class BeatleForm (InstrumentForm, PersonForm):
...
haircut_type = forms.CharField()
>>> b = BeatleForm(auto_id=False)
>>> print (b.as_ul())
<li>First name: <input type="text" name="first_name" required /></li>
<li>Last name: <input type="text" name="last_name" required /></li>
<li>Instrument: <input type="text" name="instrument" required /></li>
<li>Haircut type: <input type="text" name="haircut_type" required /></li>
It’s possible to declaratively remove a Field inherited from a parent class by setting the name of the field to None on the subclass. For example:
>>> from django import forms
>>> class ParentForm (forms.Form):
...
name = forms.CharField()
...
age = forms.IntegerField()
>>> class ChildForm (ParentForm):
...
name = None
>>> list (ChildForm().fields)
['age']
Prefixes for forms
Form.prefix
1050 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
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" required /></li>
<li><label for="id_mother-last_name">Last name:</label> <input type="text" name=
˓→
"mother-last_name" id="id_mother-last_name" required /></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" required /></li>
<li><label for="id_father-last_name">Last name:</label> <input type="text" name=
˓→
"father-last_name" id="id_father-last_name" required /></li>
The prefix can also be specified on the form class:
>>> class PersonForm (forms.Form):
...
...
...
prefix = 'person'
6.12.2 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]' )
'[email protected]'
>>> f.clean( 'invalid email address' )
Traceback (most recent call last):
...
ValidationError : ['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:
6.12. Forms 1051
Django Documentation, Release 1.11.8.dev20171115160334
>>> from django import forms
>>> f = forms.CharField()
>>> f.clean( 'foo' )
'foo'
>>> f.clean( '' )
Traceback (most recent call last):
...
ValidationError : ['This field is required.']
>>> f.clean(None)
Traceback (most recent call last):
...
ValidationError : ['This field is required.']
>>> f.clean( ' ' )
' '
>>> f.clean( 0 )
'0'
>>> f.clean(True)
'True'
>>> f.clean(False)
'False'
To specify that a field is not required, pass required=False to the Field constructor:
>>> f = forms.CharField(required=False)
>>> f.clean( 'foo' )
'foo'
>>> f.clean( '' )
''
>>> f.clean(None)
''
>>> f.clean( 0 )
'0'
>>> f.clean(True)
'True'
>>> f.clean(False)
'False'
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.)
Widgets of required form fields have the required HTML attribute. Set the
Form.use_required_attribute
attribute to False to disable it. The required attribute isn’t included on forms of formsets because the browser validation may not be correct when adding and deleting formsets.
Support for the required HTML attribute was added.
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.
1052 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
Here’s a full example Form that implements label for two of its fields. We’ve specified auto_id=False to simplify the output:
>>> from django import forms
>>> class CommentForm (forms.Form):
...
name = forms.CharField(label= 'Your name' )
...
...
url = forms.URLField(label= 'Your website' , required=False) comment = forms.CharField()
>>> f = CommentForm(auto_id=False)
>>> print (f)
<tr><th>Your name:</th><td><input type="text" name="name" required /></td></tr>
<tr><th>Your website:</th><td><input type="url" name="url" /></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" required /></td></tr> label_suffix
Field.label_suffix
The label_suffix argument lets you override the form’s
label_suffix
on a per-field basis:
>>> class ContactForm (forms.Form):
...
age = forms.IntegerField()
...
...
nationality = forms.CharField() captcha_answer = forms.IntegerField(label= '2 + 2' , label_suffix= ' =' )
>>> f = ContactForm(label_suffix= '?' )
>>> print (f.as_p())
<p><label for="id_age">Age?</label> <input id="id_age" name="age" type="number"
˓→ required /></p>
<p><label for="id_nationality">Nationality?</label> <input id="id_nationality" name=
˓→
"nationality" type="text" required /></p>
<p><label for="id_captcha_answer">2 + 2 =</label> <input id="id_captcha_answer" name=
˓→
"captcha_answer" type="number" required /></p> 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
Form.initial
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:
>>> from django import forms
>>> class CommentForm (forms.Form):
...
name = forms.CharField(initial= 'Your name' )
...
...
url = forms.URLField(initial= comment = forms.CharField()
>>> f = CommentForm(auto_id=False)
'http://' )
>>> print (f)
<tr><th>Name:</th><td><input type="text" name="name" value="Your name" required /></
˓→ td></tr>
<tr><th>Url:</th><td><input type="url" name="url" value="http://" required /></td></
˓→ tr>
<tr><th>Comment:</th><td><input type="text" name="comment" required /></td></tr>
6.12. Forms 1053
Django Documentation, Release 1.11.8.dev20171115160334
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://' }
>>> f = CommentForm(default_data, auto_id=False)
>>> print (f)
<tr><th>Name:</th><td><input type="text" name="name" value="Your name" required /></
˓→ td></tr>
<tr><th>Url:</th><td><ul class="errorlist"><li>Enter a valid URL.</li></ul><input
˓→ type="url" name="url" value="http://" required /></td></tr>
<tr><th>Comment:</th><td><ul class="errorlist"><li>This field is required.</li></ul>
˓→
<input type="text" name="comment" required /></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': ['This field is required.'], 'name': ['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" required /><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
Widgets
for more information.
help_text
Field.help_text
1054 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
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()).
Like the model field’s
help_text , this value isn’t HTML-escaped in automatically-generated forms.
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:
>>> from django import forms
>>> class HelpTextContactForm (forms.Form):
...
...
subject = forms.CharField(max_length= message = forms.CharField()
100 , help_text= '100 characters max.' )
...
...
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" required />
˓→
<br /><span class="helptext">100 characters max.</span></td></tr>
<tr><th>Message:</th><td><input type="text" name="message" required /></td></tr>
<tr><th>Sender:</th><td><input type="email" name="sender" required /><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" required /> <span
˓→ class="helptext">100 characters max.</span></li>
<li>Message: <input type="text" name="message" required /></li>
<li>Sender: <input type="email" name="sender" required /> 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" required /> <span class=
˓→
"helptext">100 characters max.</span></p>
<p>Message: <input type="text" name="message" required /></p>
<p>Sender: <input type="email" name="sender" required /> 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:
>>> from django import forms
>>> generic = forms.CharField()
>>> generic.clean( '' )
Traceback (most recent call last):
...
ValidationError : ['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 : ['Please enter your name']
6.12. Forms 1055
Django Documentation, Release 1.11.8.dev20171115160334
In the
built-in Field classes
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
validators documentation
for more information.
localize
Field.localize
The localize argument enables the localization of form data input, as well as the rendered output.
See the
format localization
documentation for more information.
disabled
Field.disabled
The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users. Even if a user tampers with the field’s value submitted to the server, it will be ignored in favor of the value from the form’s initial data.
Checking if the field data has changed has_changed()
Field.has_changed()
The has_changed() method is used to determine if the field value has changed from the initial value. Returns
True or False.
See the
Form.has_changed()
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:
CheckboxInput
• Empty value: False
1056 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
• 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:
TextInput
• Empty value: Whatever you’ve given as
empty_value .
• 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 three 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.
strip
If True (default), the value will be stripped of leading and trailing whitespace.
empty_value
The value to use to represent “empty”. Defaults to an empty string.
ChoiceField class ChoiceField(**kwargs)
• Default widget:
Select
• 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 argument: choices
Either an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field, or a callable that returns such an iterable. This argument accepts the same formats as the choices argument to a model field. See
6.12. Forms 1057
Django Documentation, Release 1.11.8.dev20171115160334
the
model field reference documentation on choices
for more details. If the argument is a callable, it is evaluated each time the field’s form is initialized. Defaults to an empty list.
TypedChoiceField class TypedChoiceField(**kwargs)
Just like a
ChoiceField , except
TypedChoiceField
takes two extra arguments,
coerce
and
empty_value .
• Default widget:
Select
• 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. Note that coercion happens after input validation, so it is possible to coerce to a value not present in choices.
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:
DateInput
• Empty value: None
• Normalizes to: A Python datetime.date object.
• 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
USE_L10N=False
in your settings, the following will also be included in the default input formats:
1058 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
[ '%b %d %Y' ,
'%b %d, %Y' ,
'%d %b %Y' ,
'%d %b, %Y' ,
'%B %d %Y' ,
'%B %d, %Y' ,
'%d %B %Y' ,
'%d %B, %Y' ]
See also
format localization .
# 'Oct 25 2006'
# 'Oct 25, 2006'
# '25 Oct 2006'
# '25 Oct, 2006'
# 'October 25 2006'
# 'October 25, 2006'
# '25 October 2006'
# '25 October, 2006'
DateTimeField class DateTimeField(**kwargs)
• Default widget:
DateTimeInput
• 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'
See also
format localization .
DecimalField class DecimalField(**kwargs)
• Default widget:
NumberInput
when
Field.localize
is False, else
TextInput .
• 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
6.12. Forms 1059
Django Documentation, Release 1.11.8.dev20171115160334
The max_value and min_value error messages may contain %(limit_value)s, which will be substituted by the appropriate limit.
Similarly, the max_digits, max_decimal_places and max_whole_digits error messages may contain %(max)s.
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.
DurationField class DurationField(**kwargs)
• Default widget:
TextInput
• Empty value: None
• Normalizes to: A Python timedelta .
• Validates that the given value is a string which can be converted into a timedelta.
• Error message keys: required, invalid.
Accepts any format understood by
parse_duration() .
EmailField class EmailField(**kwargs)
• Default widget:
EmailInput
• 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:
ClearableFileInput
• Empty value: None
• Normalizes to: An UploadedFile object that wraps the file content and file name into a single object.
1060 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
• 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
file uploads documentation .
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:
Select
• 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 five 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
allow_folders
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
allow_files
must be True.
FloatField class FloatField(**kwargs)
• Default widget:
NumberInput
when
Field.localize
is False, else
TextInput .
• Empty value: None
• Normalizes to: A Python float.
6.12. Forms 1061
Django Documentation, Release 1.11.8.dev20171115160334
• Validates that the given value is a 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:
ClearableFileInput
• 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
Pillow.
• Error message keys: required, invalid, missing, empty, invalid_image
Using an ImageField requires that Pillow is installed with support for the image formats you use. If you encounter a corrupt image error when you upload an image, it usually means that Pillow doesn’t understand its format. To fix this, install the appropriate library and reinstall Pillow.
When you use an ImageField on a form, you must also remember to
bind the file data to the form .
After the field has been cleaned and validated, the UploadedFile object will have an additional image attribute containing the Pillow Image instance used to check if the file was a valid image. Also, UploadedFile.
content_type will be updated with the image’s content type if Pillow can determine it, otherwise it will be set to None.
IntegerField class IntegerField(**kwargs)
• Default widget:
NumberInput
when
Field.localize
is False, else
TextInput .
• 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.
1062 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
GenericIPAddressField class GenericIPAddressField(**kwargs)
A field containing either an IPv4 or an IPv6 address.
• Default widget:
TextInput
• 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:
SelectMultiple
• 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 .
TypedMultipleChoiceField class TypedMultipleChoiceField(**kwargs)
Just like a
MultipleChoiceField , except TypedMultipleChoiceField
takes two extra arguments, coerce and empty_value.
• Default widget:
SelectMultiple
• 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.
6.12. Forms 1063
Django Documentation, Release 1.11.8.dev20171115160334
• 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:
NullBooleanSelect
• 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:
TextInput
• 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, min_length, and strip, which work just as they do for
CharField .
strip
Defaults to False. If enabled, stripping will be applied before the regex validation.
SlugField class SlugField(**kwargs)
• Default widget:
TextInput
• 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
SlugField
in forms.
Takes an optional parameter:
1064 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
allow_unicode
A boolean instructing the field to accept Unicode letters in addition to ASCII letters. Defaults to False.
TimeField class TimeField(**kwargs)
• Default widget:
TextInput
• 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:
URLInput
• 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.
UUIDField class UUIDField(**kwargs)
• Default widget:
TextInput
• Empty value: '' (an empty string)
• Normalizes to: A UUID object.
• Error message keys: required, invalid
This field will accept any string format accepted as the hex argument to the UUID constructor.
6.12. Forms 1065
Django Documentation, Release 1.11.8.dev20171115160334
Slightly complex built-in Field classes
ComboField class ComboField(**kwargs)
• Default widget:
TextInput
• Empty value: '' (an empty string)
• Normalizes to: A Unicode object.
• Validates 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).
>>> from django.forms
import ComboField
>>> f = ComboField(fields=[CharField(max_length= 20 ), EmailField()])
>>> f.clean( '[email protected]' )
'[email protected]'
>>> f.clean( '[email protected]' )
Traceback (most recent call last):
...
ValidationError : ['Ensure this value has at most 20 characters (it has 28).']
MultiValueField class MultiValueField(fields=(), **kwargs)
• Default widget:
TextInput
• Empty value: '' (an empty string)
• Normalizes to: the type returned by the compress method of the subclass.
• Validates the given value against each of the fields specified as an argument to the MultiValueField.
• Error message keys: required, invalid, incomplete
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
MultiValueField
must not implement
clean()
but instead - implement
compress() .
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
compress() .
Also takes some optional arguments: require_all_fields
Defaults to True, in which case a required validation error will be raised if no value is supplied for any field.
1066 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
When set to False, the
Field.required
attribute can be set to False for individual fields to make them optional. If no value is supplied for a required field, an incomplete validation error will be raised.
A default incomplete error message can be defined on the
MultiValueField
subclass, or different messages can be defined on each individual field. For example: from django.core.validators
import RegexValidator class PhoneField (MultiValueField): def __init__ ( self , *args, **kwargs):
# Define one message for all fields.
error_messages = {
'incomplete' : 'Enter a country calling code and a phone number.' ,
}
# Or define a different message for each field.
fields = (
CharField( error_messages={ 'incomplete' : 'Enter a country calling code.' }
˓→
, validators=[
RegexValidator( r'^[0-9]+$' , 'Enter a valid country
˓→ calling code.' ),
],
),
CharField( error_messages={ 'incomplete' : 'Enter a phone number.' }, validators=[RegexValidator( r'^[0-9]+$' , 'Enter a valid phone
˓→ number.' )],
),
CharField(
˓→ extension.' )], validators=[RegexValidator( r'^[0-9]+$' , 'Enter a valid required=False,
),
) super (PhoneField, self ). __init__ ( error_messages=error_messages, fields=fields, require_all_fields=False, *args, **kwargs
) widget
Must be a subclass of
django.forms.MultiWidget
. Default value is
TextInput , which probably
is not very useful in this case.
compress ( data_list)
Takes a list of valid values and returns a “compressed” version of those values – in a single value. For example,
SplitDateTimeField
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:
SplitDateTimeWidget
• Empty value: None
6.12. Forms 1067
Django Documentation, Release 1.11.8.dev20171115160334
• 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:
ModelChoiceField
and
ModelMultipleChoiceField . 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.
For more complex uses, you can specify queryset=None when declaring the form field and then populate the queryset in the form’s __init__() method: class FooMultipleChoiceForm (forms.Form): foo_select = forms.ModelMultipleChoiceField(queryset=None) def __init__ ( self , *args, **kwargs): super (FooMultipleChoiceForm, self ). __init__ (*args, **kwargs) self .
fields[ 'foo_select' ].queryset = ...
ModelChoiceField class ModelChoiceField(**kwargs)
• Default widget:
Select
• 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.
A single argument is required: queryset
A QuerySet of model objects from which the choices for the field are derived and which is used to validate the user’s selection. It’s evaluated when the form is rendered.
1068 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
ModelChoiceField also takes two optional arguments: 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).
to_field_name
This optional argument is used to specify the field to use as the value of the choices in the field’s widget.
Be sure it’s a unique field for the model, otherwise the selected value could match more than one object.
By default it is set to None, in which case the primary key of each object will be used. For example:
# No custom to_field_name field1 = forms.ModelChoiceField(queryset=...) would yield:
< select id = "id_field1" name = "field1" >
< option value = "obj1.pk" >Object1</ option >
< option value = "obj2.pk" >Object2</ option >
...
</ select > and:
# to_field_name provided field2 = forms.ModelChoiceField(queryset=..., to_field_name= "name" ) would yield:
< select id = "id_field2" name = "field2" >
< option value = "obj1.name" >Object1</ option >
< option value = "obj2.name" >Object2</ option >
...
</ select >
The __str__ (__unicode__ on Python 2) 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: from django.forms
import ModelChoiceField class MyModelChoiceField (ModelChoiceField): def label_from_instance ( self , obj): return "My Object #%i" % obj.id
6.12. Forms 1069
Django Documentation, Release 1.11.8.dev20171115160334
ModelMultipleChoiceField class ModelMultipleChoiceField(**kwargs)
• Default widget:
SelectMultiple
• 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 invalid_choice message may contain %(value)s and the invalid_pk_value message may contain %(pk)s, which will be substituted by the appropriate values.
Allows the selection of one or more model objects, suitable for representing a many-to-many relation. As with
ModelChoiceField , you can use label_from_instance to customize the object representations.
A single argument is required: queryset
Same as
ModelChoiceField.queryset
.
Takes one optional argument: to_field_name
Same as
ModelChoiceField.to_field_name
.
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 and that its __init__() method accept the core arguments mentioned above (required, label, initial, widget , help_text).
You can also customize how a field will be accessed by overriding
get_bound_field() .
6.12.3 Model Form Functions
Model Form API reference. For introductory material about model forms, see the
Creating forms from models
topic guide.
modelform_factory modelform_factory ( model , form=ModelForm, fields=None, exclude=None, formfield_callback=None, widgets=None , localized_fields=None , labels=None , help_texts=None , error_messages=None , field_classes=None)
Returns a
ModelForm
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.
formfield_callback is a callable that takes a model field and returns a form field.
1070 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
widgets is a dictionary of model field names mapped to a widget.
localized_fields is a list of names of fields which should be localized.
labels is a dictionary of model field names mapped to a label.
help_texts is a dictionary of model field names mapped to a help text.
error_messages is a dictionary of model field names mapped to a dictionary of error messages.
field_classes is a dictionary of model field names mapped to a form field class.
See
ModelForm factory function
for example usage.
You must provide the list of fields explicitly, either via keyword arguments fields or exclude, or the corresponding attributes on the form’s inner Meta class. See
Selecting the fields to use
for more information.
Omitting any definition of the fields to use will result in an
ImproperlyConfigured
exception.
modelformset_factory 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 , widgets=None , validate_max=False , localized_fields=None , labels=None , help_texts=None , min_num=None , validate_min=False , error_messages=None , field_classes=None)
Returns a FormSet class for the given model class.
Arguments model , form , fields , exclude , formfield_callback , widgets , localized_fields , labels, help_texts, error_messages, and field_classes are all passed through to
modelform_factory() .
Arguments formset, extra, max_num, can_order, can_delete and validate_max are passed through to
formset_factory() . See
formsets
for details.
See
Model formsets
for example usage.
inlineformset_factory 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 , widgets=None , validate_max=False , localized_fields=None , labels=None , help_texts=None , error_messages=None , min_num=None , validate_min=False , field_classes=None)
Returns an InlineFormSet using
modelformset_factory()
with defaults of
formset= BaseInlineFormSet , can_delete=True, and extra=3.
If your model has more than one
ForeignKey
to the parent_model, you must specify a fk_name.
See
Inline formsets
for example usage.
6.12.4 Formset Functions
Formset API reference. For introductory material about formsets, see the
Formsets
topic guide.
6.12. Forms 1071
Django Documentation, Release 1.11.8.dev20171115160334
formset_factory formset_factory ( form , formset=BaseFormSet , extra=1 , can_order=False , can_delete=False , max_num=None , validate_max=False, min_num=None, validate_min=False)
Returns a FormSet class for the given form class.
See
formsets
for example usage.
6.12.5 The form rendering API
In older versions, widgets are rendered using Python. All APIs described in this document are new.
Django’s form widgets are rendered using Django’s
template engines system .
The form rendering process can be customized at several levels:
• Widgets can specify custom template names.
• Forms and widgets can specify custom renderer classes.
• A widget’s template can be overridden by a project. (Reusable applications typically shouldn’t override built-in templates because they might conflict with a project’s custom templates.)
The low-level render API
The rendering of form templates is controlled by a customizable renderer class. A custom renderer can be specified by updating the
FORM_RENDERER
setting. It defaults to ' django.forms.renderers.DjangoTemplates
'
.
You can also provide a custom renderer by setting the
Form.default_renderer
attribute or by using the renderer argument of
Widget.render() .
Use one of the
built-in template form renderers
or implement your own. Custom renderers must implement a render(template_name, context, request=None) method. It should return a rendered templates (as a string) or raise
TemplateDoesNotExist .
Built-in-template form renderers
DjangoTemplates class DjangoTemplates
This renderer uses a standalone
DjangoTemplates
engine (unconnected to what you might have configured in the
TEMPLATES
setting). It loads templates first from the built-in form templates directory in django/forms/ templates and then from the installed apps’ templates directories using the
app_directories
loader.
If you want to render templates with customizations from your
TEMPLATES
setting, such as context processors for example, use the
TemplatesSetting
renderer.
Jinja2 class Jinja2
This renderer is the same as the
DjangoTemplates
renderer except that it uses a
Jinja2
backend. Templates for the built-in widgets are located in django/forms/jinja2 and installed apps can provide templates in a jinja2 directory.
1072 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
To use this backend, all the widgets in your project and its third-party apps must have Jinja2 templates. Unless you provide your own Jinja2 templates for widgets that don’t have any, you can’t use this renderer. For example,
django.
contrib.admin
doesn’t include Jinja2 templates for its widgets due to their usage of Django template tags.
TemplatesSetting class TemplatesSetting
This renderer gives you complete control of how widget templates are sourced. It uses
get_template()
to find widget templates based on what’s configured in the
TEMPLATES
setting.
Using this renderer along with the built-in widget templates requires either:
• 'django.forms' in
INSTALLED_APPS
and at least one engine with
APP_DIRS=True .
• Adding the built-in widgets templates directory in
DIRS
of one of your template engines. To generate that path: import django django.__path__[ 0 ] + '/forms/templates' # or '/forms/jinja2'
Using this renderer requires you to make sure the form templates your project needs can be located.
Context available in widget templates
Widget templates receive a context from
Widget.get_context() . By default, widgets receive a single value in
the context, widget. This is a dictionary that contains values like:
• name
• value
• attrs
• is_hidden
• template_name
Some widgets add further information to the context.
For instance, all widgets that subclass Input defines widget['type'] and
MultiWidget
defines widget['subwidgets'] for looping purposes.
Overriding built-in widget templates
Each widget has a template_name attribute with a value such as input.html. Built-in widget templates are stored in the django/forms/widgets path. You can provide a custom template for input.html by defining django/forms/widgets/input.html, for example. See
Built-in widgets
for the name of each widget’s template.
If you use the
TemplatesSetting
renderer, overriding widget templates works the same as overriding any other template in your project. You can’t override built-in widget templates using the other built-in renderers.
6.12.6 Widgets
A widget is Django’s representation of an 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.
The HTML generated by the built-in widgets uses HTML5 syntax, targeting <!DOCTYPE html>. For example, it uses boolean attributes such as checked rather than the XHTML style of checked='checked'.
6.12. Forms 1073
Django Documentation, Release 1.11.8.dev20171115160334
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
assigned
to form fields.
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
Built-in Field classes .
However, if you want to use a different widget for a field, you can just use the
widget
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
Textarea
widget, rather than the default
TextInput
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
years
attribute is set for a
SelectDateWidget :
from django import forms
BIRTH_YEAR_CHOICES = ( '1980' , '1981' , '1982' )
FAVORITE_COLORS_CHOICES = (
( 'blue' , 'Blue' ),
( 'green' , 'Green' ),
( 'black' , 'Black' ),
) class SimpleForm (forms.Form): birth_year = forms.DateField(widget=forms.SelectDateWidget(years=BIRTH_YEAR_
˓→
CHOICES)) favorite_colors = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES,
)
See the
Built-in widgets
for more information about which widgets are available and which arguments they accept.
Widgets inheriting from the Select widget
Widgets inheriting from the
Select
widget deal with choices. They present the user with a list of options to choose from. The different widgets present this choice differently; the
Select
widget itself uses a <select> HTML list representation, while
RadioSelect
uses radio buttons.
1074 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
Select
widgets are used by default on
ChoiceField
fields. The choices displayed on the widget are inherited from the
ChoiceField
and changing
ChoiceField.choices
will update
Select.choices
. For example:
>>> 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' ,),)
>>> choice_field.widget.choices
[('1', 'First and only')]
Widgets which offer a
choices
attribute can however be used with fields which are not based on choice – such as a
CharField
– but it is recommended to use a
ChoiceField -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
TextInput
widgets will appear the same on your Web pages.
There are two ways to customize widgets:
per widget instance
and
per widget class .
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
TextInput
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" required /></td></tr>
<tr><th>Url:</th><td><input type="url" name="url" required /></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" required /></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
Widget.attrs
argument when creating the widget:
6.12. Forms 1075
Django Documentation, Release 1.11.8.dev20171115160334
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()
<tr><th>Name:</th><td><input type="text" name="name" class="special" required /></td>
˓→
</tr>
<tr><th>Url:</th><td><input type="url" name="url" required /></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" size="40" required /></td>
˓→
</tr>
You can also set the HTML id using
attrs . See
BoundField.id_for_label
for an example.
Styling widget classes
With widgets, it is possible to add assets (css and javascript) and more deeply customize their appearance and behavior.
In a nutshell, you will need to subclass the widget and either
define a “Media” inner class
or
create a “media” property .
These methods involve somewhat advanced Python programming and are described in detail in the
Form Assets
topic guide.
Base widget classes
Base widget classes
Widget
and
MultiWidget
are subclassed by all the
built-in widgets
and may serve as a foundation for custom widgets.
Widget class Widget(attrs=None)
This abstract class cannot be rendered, but provides the basic attribute
attrs . You may also implement or
override the
render()
method on custom widgets.
attrs
A dictionary containing HTML attributes to be set on the rendered widget.
>>> from django import forms
>>> name = forms.TextInput(attrs={ 'size' : 10 , 'title' : 'Your name' ,})
>>> name.render( 'name' , 'A name' )
'<input title="Your name" type="text" name="name" value="A name" size="10"
˓→ required />'
If you assign a value of True or False to an attribute, it will be rendered as an HTML5 boolean attribute:
>>> name = forms.TextInput(attrs={ 'required' : True})
>>> name.render( 'name' , 'A name' )
'<input name="name" type="text" value="A name" required />'
>>>
1076 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
>>> name = forms.TextInput(attrs={ 'required' : False})
>>> name.render( 'name' , 'A name' )
'<input name="name" type="text" value="A name" />' supports_microseconds
An attribute that defaults to True. If set to False, the microseconds part of datetime and time values will be set to 0.
format_value ( value)
Cleans and returns a value for use in the widget template. value isn’t guaranteed to be valid input, therefore subclass implementations should program defensively.
In older versions, this method is a private API named _format_value(). The old name will work until
Django 2.0.
get_context ( name , value, attrs)
Returns a dictionary of values to use when rendering the widget template. By default, the dictionary contains a single key, 'widget', which is a dictionary representation of the widget containing the following keys:
• 'name': The name of the field from the name argument.
• 'is_hidden': A boolean indicating whether or not this widget is hidden.
• 'required': A boolean indicating whether or not the field for this widget is required.
• 'value': The value as returned by
format_value() .
• 'attrs': HTML attributes to be set on the rendered widget. The combination of the
attrs
attribute and the attrs argument.
• 'template_name': The value of self.template_name.
Widget subclasses can provide custom context values by overriding this method.
id_for_label ( id_)
Returns the HTML ID attribute of this widget for use by a <label>, given the ID of the field. Returns
None if an ID isn’t available.
This hook is necessary because some widgets have multiple HTML elements and, thus, multiple IDs. In that case, this method should return an ID value that corresponds to the first ID in the widget’s tags.
render ( name , value, attrs=None, renderer=None)
Renders a widget to HTML using the given renderer. If renderer is None, the renderer from the
FORM_RENDERER
setting is used.
The renderer argument was added. Support for subclasses that don’t accept it will be removed in
Django 2.1.
value_from_datadict ( data , files, name)
Given a dictionary of data and this widget’s name, returns the value of this widget. files may contain data coming from
request.FILES
. Returns None if a value wasn’t provided. Note also that
value_from_datadict may be called more than once during handling of form data, so if you customize it and add expensive processing, you should implement some caching mechanism yourself.
value_omitted_from_data ( data , files, name)
Given data and files dictionaries and this widget’s name, returns whether or not there’s data or files for the widget.
The method’s result affects whether or not a field in a model form
falls back to its default .
Special cases are
CheckboxInput ,
CheckboxSelectMultiple , and
SelectMultiple , which
always return False because an unchecked checkbox and unselected <select multiple> don’t
6.12. Forms 1077
Django Documentation, Release 1.11.8.dev20171115160334
appear in the data of an HTML form submission, so it’s unknown whether or not the user submitted a value.
use_required_attribute ( initial)
Given a form field’s initial value, returns whether or not the widget can be rendered with the required HTML attribute.
Forms use this method along with
Field.required
and
Form.
use_required_attribute
to determine whether or not to display the required attribute for each field.
By default, returns False for hidden widgets and True otherwise.
Special cases are
ClearableFileInput ,
which returns False when initial is not set, and
CheckboxSelectMultiple , which always returns False because browser validation would
require all checkboxes to be checked instead of at least one.
Override this method in custom widgets that aren’t compatible with browser validation. For example, a
WSYSIWG text editor widget backed by a hidden textarea element may want to always return False to avoid browser validation on the hidden field.
MultiWidget class MultiWidget(widgets, attrs=None)
A widget that is composed of multiple widgets.
MultiWidget
works hand in hand with the
MultiValueField .
MultiWidget
has one required argument: widgets
An iterable containing the widgets needed.
And one required method: 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
SplitDateTimeWidget
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
MultiValueField
has a complementary method
compress()
with the opposite responsibility - to combine cleaned values of all member fields into one.
1078 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
It provides some custom context: get_context ( name , value, attrs)
In addition to the 'widget' key described in
Widget.get_context() , MultiValueWidget
adds a widget['subwidgets'] key.
These can be looped over in the widget template:
{% for subwidget in widget.subwidgets
%}
{% include widget.template_name
with widget = subwidget %}
{% endfor %}
Here’s an example widget which subclasses
MultiWidget
to display a date with the day, month, and year in different select boxes.
This widget is intended to be used with a
DateField
rather than a
MultiValueField , thus we have implemented
value_from_datadict() :
from datetime import date from django.forms
import widgets 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 value_from_datadict ( self , data, files, name): datelist = [ try : widget.value_from_datadict(data, files, name + '_%s' % i) 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
Select
widgets in a tuple. The super class uses this tuple to setup the widget.
The required method
decompress()
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
value_from_datadict()
returns a list of values corresponding to each
Widget . This is appropriate when using a MultiWidget with a
MultiValueField , but since we want to
use this widget with a
DateField
which takes a single value, we have overridden this method to combine the
6.12. Forms 1079
Django Documentation, Release 1.11.8.dev20171115160334
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
the input of text ,
various checkboxes and selectors ,
uploading files ,
and
handling of multi-valued input .
Widgets handling input of text
These widgets make use of the HTML elements input and textarea.
TextInput class TextInput
• input_type: 'text'
• template_name: 'django/forms/widgets/text.html'
• Renders as: <input type="text" ...>
NumberInput class NumberInput
• input_type: 'number'
• template_name: 'django/forms/widgets/number.html'
• Renders as: <input type="number" ...>
Beware that not all browsers support entering localized numbers in number input types. Django itself avoids using them for fields having their
localize
property set to True.
EmailInput class EmailInput
• input_type: 'email'
• template_name: 'django/forms/widgets/email.html'
• Renders as: <input type="email" ...>
URLInput class URLInput
• input_type: 'url'
• template_name: 'django/forms/widgets/url.html'
1080 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
• Renders as: <input type="url" ...>
PasswordInput class PasswordInput
• input_type: 'password'
• template_name: 'django/forms/widgets/password.html'
• Renders as: <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
• input_type: 'hidden'
• template_name: 'django/forms/widgets/hidden.html'
• Renders as: <input type="hidden" ...>
Note that there also is a
MultipleHiddenInput
widget that encapsulates a set of hidden input elements.
DateInput class DateInput
• input_type: 'text'
• template_name: 'django/forms/widgets/date.html'
• Renders as: <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
DATE_INPUT_FORMATS
and respects
Format localization .
DateTimeInput class DateTimeInput
• input_type: 'text'
• template_name: 'django/forms/widgets/datetime.html'
• Renders as: <input type="text" ...>
Takes same arguments as
TextInput , with one more optional argument:
6.12. Forms 1081
Django Documentation, Release 1.11.8.dev20171115160334
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
DATETIME_INPUT_FORMATS
and respects
Format localization .
By default, the microseconds part of the time value is always set to 0. If microseconds are required, use a subclass with the
supports_microseconds
attribute set to True.
TimeInput class TimeInput
• input_type: 'text'
• template_name: 'django/forms/widgets/time.html'
• Renders as: <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
TIME_INPUT_FORMATS
and respects
Format localization .
For the treatment of microseconds, see
DateTimeInput .
Textarea class Textarea
• template_name: 'django/forms/widgets/textarea.html'
• Renders as: <textarea>...</textarea>
Selector and checkbox widgets
These widgets make use of the HTML elements <select>, <input type="checkbox">, and <input type="radio"> .
Widgets that render multiple choices have an option_template_name attribute that specifies the template used to render each choice. For example, for the
Select
widget, select_option.html renders the <option> for a
<select> .
CheckboxInput class CheckboxInput
• input_type: 'checkbox'
• template_name: 'django/forms/widgets/checkbox.html'
• Renders as: <input type="checkbox" ...>
Takes one optional argument:
1082 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
check_test
A callable that takes the value of the CheckboxInput and returns True if the checkbox should be checked for that value.
Select class Select
• template_name: 'django/forms/widgets/select.html'
• option_template_name: 'django/forms/widgets/select_option.html'
• Renders as: <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
Field .
NullBooleanSelect class NullBooleanSelect
• template_name: 'django/forms/widgets/select.html'
• option_template_name: 'django/forms/widgets/select_option.html'
Select widget with options ‘Unknown’, ‘Yes’ and ‘No’
SelectMultiple class SelectMultiple
• template_name: 'django/forms/widgets/select.html'
• option_template_name: 'django/forms/widgets/select_option.html'
Similar to
Select , but allows multiple selection: <select multiple="multiple">...</select>
RadioSelect class RadioSelect
• template_name: 'django/forms/widgets/radio.html'
• option_template_name: 'django/forms/widgets/radio_option.html'
Similar to
Select , but rendered as a list of radio buttons within <li> tags:
< ul >
< li >< input type = "radio" name = "..." ></ 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:
6.12. Forms 1083
Django Documentation, Release 1.11.8.dev20171115160334
1084
{% for radio in myform.beatles
%}
< div class = "myradio" >
{{ radio }}
</ div >
{% endfor %}
This would generate the following HTML:
< div class = "myradio" >
< label for = "id_beatles_0" >< input id = "id_beatles_0" name = "beatles" type = "radio
˓→
" value = "john" required /> John</ label >
</ div >
< div class = "myradio" >
< label for = "id_beatles_1" >< input id = "id_beatles_1" name = "beatles" type = "radio
˓→
" value = "paul" required /> Paul</ label >
</ div >
< div class = "myradio" >
< label for = "id_beatles_2" >< input id = "id_beatles_2" name = "beatles" type = "radio
˓→
" value = "george" required /> George</ label >
</ div >
< div class = "myradio" >
< label for = "id_beatles_3" >< input id = "id_beatles_3" name = "beatles" type = "radio
˓→
" value = "ringo" required /> Ringo</ label >
</ div >
That included the <label> tags. To get more granular, you can use each radio button’s tag, choice_label and id_for_label attributes. For example, this template...
{% for radio in myform.beatles
%}
< label for = " {{ radio.id_for_label
}} " >
{{ radio.choice_label
}}
< span class = "radio" > {{ radio.tag
}} </ span >
</ label >
{% endfor %}
...will result in the following HTML:
< label for = "id_beatles_0" >
John
< span class = "radio" >< input id = "id_beatles_0" name = "beatles" type = "radio"
˓→ value = "john" required /></ span >
</ label >
< label for = "id_beatles_1" >
Paul
< span class = "radio" >< input id = "id_beatles_1" name = "beatles" type = "radio"
˓→ value = "paul" required /></ span >
</ label >
< label for = "id_beatles_2" >
George
< span class = "radio" >< input id = "id_beatles_2" name = "beatles" type = "radio"
˓→ value = "george" required /></ span >
</ label >
< label for = "id_beatles_3" >
Ringo
< span class = "radio" >< input id = "id_beatles_3" name = "beatles" type = "radio"
˓→ value = "ringo" required /></ span >
Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
</ 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.
The outer <ul> container receives the id attribute of the widget, if defined, or
BoundField.auto_id
otherwise.
When looping over the radio buttons, the label and input tags include for and id attributes, respectively.
Each radio button has an id_for_label attribute to output the element’s ID.
CheckboxSelectMultiple class CheckboxSelectMultiple
• template_name: 'django/forms/widgets/checkbox_select.html'
• option_template_name: 'django/forms/widgets/checkbox_option.html'
Similar to
SelectMultiple , but rendered as a list of check buttons:
< ul >
< li >< input type = "checkbox" name = "..." ></ li >
...
</ ul >
The outer <ul> container receives the id attribute of the widget, if defined, or
BoundField.auto_id
otherwise.
Like
RadioSelect , you can loop over the individual checkboxes for the widget’s choices. Unlike RadioSelect ,
the checkboxes won’t include the required HTML attribute if the field is required because browser validation would require all checkboxes to be checked instead of at least one.
When looping over the checkboxes, the label and input tags include for and id attributes, respectively. Each checkbox has an id_for_label attribute to output the element’s ID.
File upload widgets
FileInput class FileInput
• template_name: 'django/forms/widgets/file.html'
• Renders as: <input type="file" ...>
ClearableFileInput class ClearableFileInput
• template_name: 'django/forms/widgets/clearable_file_input.html'
• Renders as: <input type="file" ...> with an additional checkbox input to clear the field’s value, if the field is not required and has initial data.
6.12. Forms 1085
Django Documentation, Release 1.11.8.dev20171115160334
Composite widgets
MultipleHiddenInput class MultipleHiddenInput
• template_name: 'django/forms/widgets/multiple_hidden.html'
• Renders as: multiple <input type="hidden" ...> tags
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
Field .
SplitDateTimeWidget class SplitDateTimeWidget
• template_name: 'django/forms/widgets/splitdatetime.html'
Wrapper (using
MultiWidget ) around two widgets:
DateInput
for the date, and
TimeInput
for the time. Must be used with
SplitDateTimeField
rather than
DateTimeField .
SplitDateTimeWidget has two optional attributes: date_format
Similar to
DateInput.format
time_format
Similar to
TimeInput.format
SplitHiddenDateTimeWidget class SplitHiddenDateTimeWidget
• template_name: 'django/forms/widgets/splithiddendatetime.html'
Similar to
SplitDateTimeWidget , but uses
HiddenInput
for both date and time.
SelectDateWidget class SelectDateWidget
• template_name: 'django/forms/widgets/select_date.html'
Wrapper around three
Select
widgets: one each for month, day, and year.
Takes several optional arguments: 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.
months
An optional dict of months to use in the “months” select box.
The keys of the dict correspond to the month number (1-indexed) and the values are the displayed months:
1086 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
MONTHS = {
1 :_( 'jan' ), 2 :_( 'feb' ), 3 :_( 'mar' ), 4 :_( 'apr' ),
5 :_( 'may' ), 6 :_( 'jun' ), 7 :_( 'jul' ), 8 :_( 'aug' ),
9 :_( 'sep' ), 10 :_( 'oct' ), 11 :_( 'nov' ), 12 :_( 'dec' )
} empty_label
If the
DateField
is not required,
SelectDateWidget
will have an empty choice at the top of the list (which is --- by default). You can change the text of this label with the empty_label attribute.
empty_label can be a string, list, or tuple. When a string is used, all select boxes will each have an empty choice with this label. If empty_label is a list or tuple of 3 string elements, the select boxes will have their own custom label. The labels should be in this order ('year_label',
'month_label', 'day_label') .
# A custom empty label with string field1 = forms.DateField(widget=SelectDateWidget(empty_label= "Nothing" ))
# A custom empty label with tuple field1 = forms.DateField( widget=SelectDateWidget( empty_label=( "Choose Year" , "Choose Month" , "Choose Day" ),
),
)
6.12.7 Form and field validation
Form validation happens when the data is cleaned. If you want to customize this process, there are various places to make changes, 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 also 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 information to the ValidationError constructor.
See below
for the best practice in raising
ValidationError . If no ValidationError is raised, the method should return the cleaned (normalized) data as a Python object.
Most validation can be done using
validators
- 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 a 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 a 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.
• 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.
6.12. Forms 1087
Django Documentation, Release 1.11.8.dev20171115160334
• The clean() method on a Field subclass 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 is called on 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.
The return value of this method replaces the existing value in cleaned_data, so it must be the field’s value from cleaned_data (even if this method didn’t change it) or a new cleaned value.
• The form subclass’s clean() method can perform validation that requires access to multiple form fields. This is where you might put in checks such as “if field A is supplied, field B must contain a valid email address”. This method can return a completely different dictionary if it wishes, which will be used as the cleaned_data.
Since the field validation methods 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 cleaning of individual fields.
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 need to call
add_error() .
Also note that there are special considerations when overriding the clean() method of a ModelForm subclass. (see the
ModelForm documentation
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 whether or not the previous methods have raised errors.
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.
Raising ValidationError
In order to make error messages flexible and easy to override, consider the following guidelines:
• Provide a descriptive error code to the constructor:
# Good
ValidationError(_( 'Invalid value' ), code= 'invalid' )
# Bad
ValidationError(_( 'Invalid value' ))
• Don’t coerce variables into the message; use placeholders and the params argument of the constructor:
1088 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
# Good
ValidationError(
_( 'Invalid value: %(value)s' ), params={ 'value' : '42' },
)
# Bad
ValidationError(_( 'Invalid value: %s' ) % value)
• Use mapping keys instead of positional formatting. This enables putting the variables in any order or omitting them altogether when rewriting the message:
# Good
ValidationError(
_( 'Invalid value: %(value)s' ), params={ 'value' : '42' },
)
# Bad
ValidationError(
_( 'Invalid value: %s' ), params=( '42' ,),
)
• Wrap the message with gettext to enable translation:
# Good
ValidationError(_( 'Invalid value' ))
# Bad
ValidationError( 'Invalid value' )
Putting it all together: raise ValidationError(
_( 'Invalid value: %(value)s' ), code= 'invalid' , params={ 'value' : '42' },
)
Following these guidelines is particularly necessary if you write reusable forms, form fields, and model fields.
While not recommended, if you are at the end of the validation chain (i.e. your form clean() method) and you know you will never need to override your error message you can still opt for the less verbose:
ValidationError(_( 'Invalid value: %s' ) % value)
The
Form.errors.as_data()
and
Form.errors.as_json()
methods greatly benefit from fully featured
ValidationError s (with a code name and a params dictionary).
Raising multiple errors
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.
As above, it is recommended to pass a list of ValidationError instances with codes and params but a list of strings will also work:
6.12. Forms 1089
Django Documentation, Release 1.11.8.dev20171115160334
# Good raise ValidationError([
ValidationError(_( 'Error 1' ), code= 'error1' ),
ValidationError(_( 'Error 2' ), code= 'error2' ),
])
# Bad raise ValidationError([
_( 'Error 1' ),
_( 'Error 2' ),
])
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
ValidationError
if not. These can be passed to a field’s constructor, via the field’s validators argument, or defined on the
Field
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 SlugField: from django.forms
import CharField from django.core
import validators class SlugField (CharField): default_validators = [validators.validate_slug]
As you can see, SlugField is just a CharField with a customized validator that validates that submitted text obeys to some character rules. This can also be done on field definition so: slug = forms.SlugField() is equivalent to: slug = forms.CharField(validators=[validators.validate_slug])
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
RegexValidator
constructed with the first argument being the pattern: ^[-a-zA-Z0-9_]+$. See the section on
writing validators
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 first create a custom form field that validates its input is a string containing comma-separated email addresses.
The full class looks like this:
1090 Chapter 6. API Reference
Django Documentation, Release 1.11.8.dev20171115160334
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: from django import forms class ContactForm (forms.Form):
# Everything as before.
...
def clean_recipients ( self ): data = self .
cleaned_data[ 'recipients' ] if "[email protected]" not in data: raise forms.ValidationError( "You have forgotten about Fred!" )
# Always return a value to use as the new cleaned data, even if
# this method didn't change it.
return data
6.12. Forms 1091
Django Documentation, Release 1.11.8.dev20171115160334
Cleaning and validating fields that depend on each other
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: from django import forms 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."
)
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.
The call to super(ContactForm, self).clean() in the example code ensures that any validation logic in parent classes is maintained. If your form inherits another that doesn’t return a cleaned_data dictionary in its clean() method (doing so is optional), then don’t assign cleaned_data to the result of the super() call and use self.cleaned_data instead: def clean ( self ): super (ContactForm, self ).clean() cc_myself = self .
cleaned_data.get( "cc_myself" )
...
The second approach for reporting validation errors might involve assigning the error message to one of the fields. In this case, let’s assign an error message to both the “subject” and “cc_myself” rows in the form display. Be careful when doing this in practice, since it can lead to confusing form output. We’re showing what is possible here and leaving it up to you and your designers to work out what works effectively in your particular situation. Our new code
(replacing the previous sample) looks like this: from django import forms class ContactForm (forms.Form):
1092 Chapter 6. API Reference