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.

Note that passing an empty dictionary creates a bound form with empty data:

>>> f=ContactForm({})>>> f.is_boundTrue

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.

In this dictionary, the keys are the field names, and the values are lists of
strings representing the error messages. The error messages are stored
in lists because a field can have multiple error messages.

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.

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.

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.

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.

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 initialand 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:

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.

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:

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:

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:

In this above example, the cleaned_data value for nick_name is set to an
empty string, because nick_name is CharField, and CharFields treat
empty values as an empty string. Each field type knows what its “blank” value
is – e.g., for DateField, it’s None instead of the empty string. For
full details on each field’s behavior in this case, see the “Empty value” note
for each field in the “Built-in Field classes” section below.

You can write code to perform validation for particular form fields (based on
their name) or for the form as a whole (considering combinations of various
fields). More information about this is in Form and field validation.

If the form is bound to data, the HTML output will include that data
appropriately. For example, if a field is represented by an
<inputtype="text">, the data will be in the value attribute. If a
field is represented by an <inputtype="checkbox">, then that HTML will
include checked if appropriate:

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 <inputtype="submit"> tag. It’s your job to do that.

Each field type has a default HTML representation. CharField is
represented by an <inputtype="text"> and EmailField by an
<inputtype="email">.
BooleanField is represented by an <inputtype="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
'Ccmyself:' is generated from the field name by converting all
underscores to spaces and upper-casing the first letter. Again, note
these are merely sensible defaults; you can also specify labels manually.

Each text label is surrounded in an HTML <label> tag, which points
to the appropriate form field via its id. Its id, in turn, is
generated by prepending 'id_' to the field name. The id
attributes and <label> tags are included in the output by default, to
follow best practices, but you can change that behavior.

The output uses HTML5 syntax, targeting <!DOCTYPEhtml>. 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 string.

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:

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:

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.

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_orderand you include field_order when instantiating
the Form, then the latter field_order will have precedence.

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 <ulclass="errorlist"> near the
field. The particular positioning of the error messages depends on the output
method you’re using:

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:

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.

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:

classGPSCoordinatesBoundField(BoundField):@propertydefcountry(self):""" Return the country the coordinates lie in or None if it can't be determined. """value=self.value()ifvalue:returnget_country_from_coordinates(value)else:returnNoneclassGPSCoordinatesField(Field):defget_bound_field(self,form,field_name):returnGPSCoordinatesBoundField(form,self,field_name)

Now you can access the country in a template with
{{form.coordinates.country}}.

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":

<formenctype="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>>>fromdjango.core.files.uploadedfileimportSimpleUploadedFile>>>data={'subject':'hello',...'message':'Hi there',...'sender':'foo@example.com',...'cc_myself':True}>>>file_data={'mugshot':SimpleUploadedFile('face.jpg',<filedata>)}>>>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:

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:

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:

This document is for Django's development version, which can be significantly different from previous releases. For older releases, use the version selector floating in the bottom right corner of this page.