=============
The Forms API
=============
.. module:: django.forms
.. admonition:: About this document
This document covers the gritty details of Django's forms API. You should
read the :doc:`introduction to working with forms `
first.
.. _ref-forms-api-bound-unbound:
Bound and unbound forms
-----------------------
A :class:`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 :class:`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 :class:`Form` class constructor::
>>> data = {'subject': 'hello',
... 'message': 'Hi there',
... 'sender': 'foo@example.com',
... 'cc_myself': True}
>>> f = ContactForm(data)
In this dictionary, the keys are the field names, which correspond to the
attributes in your :class:`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 :class:`Field`, as we'll see
in a moment.
.. attribute:: Form.is_bound
If you need to distinguish between bound and unbound form instances at runtime,
check the value of the form's :attr:`~Form.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 :class:`Form` instance and want to change the data somehow,
or if you want to bind an unbound :class:`Form` instance to some data, create
another :class:`Form` instance. There is no way to change data in a
:class:`Form` instance. Once a :class:`Form` instance has been created, you
should consider its data immutable, whether it has data or not.
Using forms to validate data
----------------------------
.. method:: Form.is_valid()
The primary task of a :class:`Form` object is to validate data. With a bound
:class:`Form` instance, call the :meth:`~Form.is_valid` method to run validation
and return a boolean designating whether the data was valid::
>>> data = {'subject': 'hello',
... 'message': 'Hi there',
... 'sender': 'foo@example.com',
... '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
.. attribute:: Form.errors
Access the :attr:`~Form.errors` attribute to get a dictionary of error
messages::
>>> f.errors
{'sender': [u'Enter a valid email address.'], 'subject': [u'This field is required.']}
In this dictionary, the keys are the field names, and the values are lists of
Unicode strings representing the error messages. The error messages are stored
in lists because a field can have multiple error messages.
You can access :attr:`~Form.errors` without having to call
:meth:`~Form.is_valid` first. The form's data will be validated the first time
either you call :meth:`~Form.is_valid` or access :attr:`~Form.errors`.
The validation routines will only get called once, regardless of how many times
you access :attr:`~Form.errors` or call :meth:`~Form.is_valid`. This means that
if validation has side effects, those side effects will only be triggered once.
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
----------------------
.. attribute:: Form.initial
Use :attr:`~Form.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 :attr:`~Form.initial` argument to a :class:`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.
Note that if a :class:`~django.forms.Field` defines :attr:`~Form.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::
>>> 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)
Name:
Url:
Comment:
Accessing "clean" data
----------------------
.. attribute:: Form.cleaned_data
Each field in a :class:`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, :class:`~django.forms.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 :class:`~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': 'Hi there',
... 'sender': 'foo@example.com',
... 'cc_myself': True}
>>> f = ContactForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data
{'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'}
Note that any text-based field -- such as ``CharField`` or ``EmailField`` --
always cleans the input into a Unicode string. We'll cover the encoding
implications later in this document.
If your data does *not* validate, the ``cleaned_data`` dictionary contains
only the valid fields::
>>> data = {'subject': '',
... 'message': 'Hi there',
... 'sender': 'invalid email address',
... 'cc_myself': True}
>>> f = ContactForm(data)
>>> f.is_valid()
False
>>> f.cleaned_data
{'cc_myself': True, 'message': u'Hi there'}
.. versionchanged:: 1.5
Until Django 1.5, the ``cleaned_data`` attribute wasn't defined at all when
the ``Form`` didn't validate.
``cleaned_data`` will always *only* contain a key for fields defined in the
``Form``, even if you pass extra data when you define the ``Form``. In this
example, we pass a bunch of extra fields to the ``ContactForm`` constructor,
but ``cleaned_data`` contains only the form's fields::
>>> data = {'subject': 'hello',
... 'message': 'Hi there',
... 'sender': 'foo@example.com',
... 'cc_myself': True,
... 'extra_field_1': 'foo',
... 'extra_field_2': 'bar',
... 'extra_field_3': 'baz'}
>>> f = ContactForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data # Doesn't contain extra_field_1, etc.
{'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'}
When the ``Form`` is valid, ``cleaned_data`` will include a key and value for
*all* its fields, even if the data didn't include a value for some optional
fields. In this example, the data dictionary doesn't include a value for the
``nick_name`` field, but ``cleaned_data`` includes it, with an empty value::
>>> class OptionalPersonForm(Form):
... first_name = CharField()
... last_name = CharField()
... nick_name = CharField(required=False)
>>> data = {'first_name': u'John', 'last_name': u'Lennon'}
>>> f = OptionalPersonForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data
{'nick_name': u'', 'first_name': u'John', 'last_name': u'Lennon'}
In this above example, the ``cleaned_data`` value for ``nick_name`` is set to an
empty string, because ``nick_name`` is ``CharField``, and ``CharField``\s 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 :doc:`/ref/forms/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)
If the form is bound to data, the HTML output will include that data
appropriately. For example, if a field is represented by an
````, the data will be in the ``value`` attribute. If a
field is represented by an ````, then that HTML will
include ``checked="checked"`` if appropriate::
>>> data = {'subject': 'hello',
... 'message': 'Hi there',
... 'sender': 'foo@example.com',
... 'cc_myself': True}
>>> f = ContactForm(data)
>>> print(f)
This default output is a two-column HTML table, with a ``
`` for each field.
Notice the following:
* For flexibility, the output does *not* include the ``
`` and
``
`` tags, nor does it include the ````
tags or an ```` tag. It's your job to do that.
* Each field type has a default HTML representation. ``CharField`` and
``EmailField`` are represented by an ````.
``BooleanField`` is represented by an ````. Note
these are merely sensible defaults; you can specify which HTML to use for
a given field by using widgets, which we'll explain shortly.
* The HTML ``name`` for each tag is taken directly from its attribute name
in the ``ContactForm`` class.
* The text label for each field -- e.g. ``'Subject:'``, ``'Message:'`` and
``'Cc myself:'`` is generated from the field name by converting all
underscores to spaces and upper-casing the first letter. Again, note
these are merely sensible defaults; you can also specify labels manually.
* Each text label is surrounded in an HTML ``