2008-08-23 22:25:40 +00:00
|
|
|
=============
|
|
|
|
The Forms API
|
|
|
|
=============
|
|
|
|
|
2013-01-01 13:12:42 +00:00
|
|
|
.. module:: django.forms
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
.. admonition:: About this document
|
|
|
|
|
|
|
|
This document covers the gritty details of Django's forms API. You should
|
2010-08-19 19:27:44 +00:00
|
|
|
read the :doc:`introduction to working with forms </topics/forms/index>`
|
2008-08-23 22:25:40 +00:00
|
|
|
first.
|
|
|
|
|
|
|
|
.. _ref-forms-api-bound-unbound:
|
|
|
|
|
|
|
|
Bound and unbound forms
|
|
|
|
-----------------------
|
|
|
|
|
|
|
|
A :class:`Form` instance is either **bound** to a set of data, or **unbound**.
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* 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.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* 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.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2009-12-25 20:51:30 +00:00
|
|
|
.. class:: Form
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
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
|
2011-04-01 16:10:22 +00:00
|
|
|
email address::
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
>>> data = {'subject': '',
|
|
|
|
... 'message': 'Hi there',
|
2011-04-01 16:10:22 +00:00
|
|
|
... 'sender': 'invalid email address',
|
2008-08-23 22:25:40 +00:00
|
|
|
... 'cc_myself': True}
|
|
|
|
>>> f = ContactForm(data)
|
|
|
|
>>> f.is_valid()
|
|
|
|
False
|
2008-09-16 05:31:00 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
.. attribute:: Form.errors
|
|
|
|
|
|
|
|
Access the :attr:`~Form.errors` attribute to get a dictionary of error
|
|
|
|
messages::
|
|
|
|
|
|
|
|
>>> f.errors
|
2014-03-22 20:30:49 +00:00
|
|
|
{'sender': ['Enter a valid email address.'], 'subject': ['This field is required.']}
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
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.
|
|
|
|
|
2013-11-29 19:38:13 +00:00
|
|
|
.. method:: Form.errors.as_data()
|
|
|
|
|
|
|
|
.. versionadded:: 1.7
|
|
|
|
|
|
|
|
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.'])]}
|
|
|
|
|
2014-02-13 18:19:13 +00:00
|
|
|
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, :meth:`~Form.errors.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``.
|
|
|
|
|
2014-02-18 19:00:09 +00:00
|
|
|
.. method:: Form.errors.as_json(escape_html=False)
|
2013-11-29 19:38:13 +00:00
|
|
|
|
|
|
|
.. versionadded:: 1.7
|
|
|
|
|
|
|
|
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"}]}
|
|
|
|
|
2014-02-18 19:00:09 +00:00
|
|
|
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.
|
|
|
|
|
2013-11-11 17:56:01 +00:00
|
|
|
.. method:: Form.add_error(field, error)
|
|
|
|
|
|
|
|
.. versionadded:: 1.7
|
|
|
|
|
|
|
|
This method allows adding errors to specific fields from within the
|
|
|
|
``Form.clean()`` method, or from outside the form altogether; for instance
|
2013-11-12 14:18:09 +00:00
|
|
|
from a view.
|
2013-11-11 17:56:01 +00:00
|
|
|
|
|
|
|
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
|
2014-04-05 22:14:53 +00:00
|
|
|
a non-field error as returned by :meth:`Form.non_field_errors()
|
|
|
|
<django.forms.Form.non_field_errors>`.
|
2013-11-11 17:56:01 +00:00
|
|
|
|
|
|
|
The ``error`` argument can be a simple string, or preferably an instance of
|
|
|
|
``ValidationError``. See :ref:`raising-validation-error` for best practices
|
|
|
|
when defining form errors.
|
|
|
|
|
|
|
|
Note that ``Form.add_error()`` automatically removes the relevant field from
|
|
|
|
``cleaned_data``.
|
|
|
|
|
2014-03-22 18:08:04 +00:00
|
|
|
.. method:: Form.has_error(field, code=None)
|
|
|
|
|
|
|
|
.. versionadded:: 1.8
|
|
|
|
|
|
|
|
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
|
|
|
|
:data:`~django.core.exceptions.NON_FIELD_ERRORS` as the ``field`` parameter.
|
|
|
|
|
2014-04-05 22:14:53 +00:00
|
|
|
.. method:: Form.non_field_errors()
|
|
|
|
|
|
|
|
This method returns the list of errors from :attr:`Form.errors
|
|
|
|
<django.forms.Form.errors>` that aren't associated with a particular field.
|
|
|
|
This includes ``ValidationError``\s that are raised in :meth:`Form.clean()
|
|
|
|
<django.forms.Form.clean>` and errors added using :meth:`Form.add_error(None,
|
|
|
|
"...") <django.forms.Form.add_error>`.
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
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
|
|
|
|
{}
|
|
|
|
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-03 18:30:54 +00:00
|
|
|
Dynamic initial values
|
|
|
|
----------------------
|
|
|
|
|
|
|
|
.. attribute:: Form.initial
|
|
|
|
|
2009-12-25 20:51:30 +00:00
|
|
|
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.
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-03 18:30:54 +00:00
|
|
|
|
2009-12-25 20:51:30 +00:00
|
|
|
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::
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-03 18:30:54 +00:00
|
|
|
|
|
|
|
>>> 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.
|
|
|
|
|
2012-12-25 14:56:22 +00:00
|
|
|
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::
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-03 18:30:54 +00:00
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
>>> from django import forms
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-03 18:30:54 +00:00
|
|
|
>>> class CommentForm(forms.Form):
|
|
|
|
... name = forms.CharField(initial='class')
|
|
|
|
... url = forms.URLField()
|
|
|
|
... comment = forms.CharField()
|
|
|
|
>>> f = CommentForm(initial={'name': 'instance'}, auto_id=False)
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f)
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-03 18:30:54 +00:00
|
|
|
<tr><th>Name:</th><td><input type="text" name="name" value="instance" /></td></tr>
|
2013-01-28 13:24:48 +00:00
|
|
|
<tr><th>Url:</th><td><input type="url" name="url" /></td></tr>
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-03 18:30:54 +00:00
|
|
|
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
|
|
|
|
|
2013-12-07 07:13:20 +00:00
|
|
|
Accessing the fields from the form
|
|
|
|
----------------------------------
|
|
|
|
|
|
|
|
.. attribute:: Form.fields
|
|
|
|
|
|
|
|
You can access the fields of :class:`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 :class:`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" /></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" /></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" /></td></tr>'
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
Accessing "clean" data
|
|
|
|
----------------------
|
|
|
|
|
2009-12-25 20:51:30 +00:00
|
|
|
.. 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
|
2008-08-23 22:25:40 +00:00
|
|
|
a variety of ways, always resulting in consistent output.
|
|
|
|
|
2009-12-25 20:51:30 +00:00
|
|
|
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.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2009-12-25 20:51:30 +00:00
|
|
|
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::
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
>>> data = {'subject': 'hello',
|
|
|
|
... 'message': 'Hi there',
|
|
|
|
... 'sender': 'foo@example.com',
|
|
|
|
... 'cc_myself': True}
|
|
|
|
>>> f = ContactForm(data)
|
|
|
|
>>> f.is_valid()
|
|
|
|
True
|
|
|
|
>>> f.cleaned_data
|
2014-03-22 20:30:49 +00:00
|
|
|
{'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
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.
|
|
|
|
|
2012-08-04 12:17:02 +00:00
|
|
|
If your data does *not* validate, the ``cleaned_data`` dictionary contains
|
|
|
|
only the valid fields::
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
>>> data = {'subject': '',
|
|
|
|
... 'message': 'Hi there',
|
2011-04-01 16:10:22 +00:00
|
|
|
... 'sender': 'invalid email address',
|
2008-08-23 22:25:40 +00:00
|
|
|
... 'cc_myself': True}
|
|
|
|
>>> f = ContactForm(data)
|
|
|
|
>>> f.is_valid()
|
|
|
|
False
|
|
|
|
>>> f.cleaned_data
|
2014-03-22 20:30:49 +00:00
|
|
|
{'cc_myself': True, 'message': 'Hi there'}
|
2012-08-04 12:17:02 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
``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.
|
2014-03-22 20:30:49 +00:00
|
|
|
{'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2012-08-04 12:17:02 +00:00
|
|
|
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
|
2008-08-23 22:25:40 +00:00
|
|
|
``nick_name`` field, but ``cleaned_data`` includes it, with an empty value::
|
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
>>> from django.forms import Form
|
2008-08-23 22:25:40 +00:00
|
|
|
>>> class OptionalPersonForm(Form):
|
|
|
|
... first_name = CharField()
|
|
|
|
... last_name = CharField()
|
|
|
|
... nick_name = CharField(required=False)
|
2014-03-22 20:30:49 +00:00
|
|
|
>>> data = {'first_name': 'John', 'last_name': 'Lennon'}
|
2008-08-23 22:25:40 +00:00
|
|
|
>>> f = OptionalPersonForm(data)
|
|
|
|
>>> f.is_valid()
|
|
|
|
True
|
|
|
|
>>> f.cleaned_data
|
2014-03-22 20:30:49 +00:00
|
|
|
{'nick_name': '', 'first_name': 'John', 'last_name': 'Lennon'}
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
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
|
2010-08-19 19:27:44 +00:00
|
|
|
fields). More information about this is in :doc:`/ref/forms/validation`.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
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()
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f)
|
2008-08-23 22:25:40 +00:00
|
|
|
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
|
|
|
|
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
|
2013-01-28 13:12:56 +00:00
|
|
|
<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" /></td></tr>
|
2008-08-23 22:25:40 +00:00
|
|
|
<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>
|
|
|
|
|
|
|
|
If the form is bound to data, the HTML output will include that data
|
|
|
|
appropriately. For example, if a field is represented by an
|
|
|
|
``<input type="text">``, the data will be in the ``value`` attribute. If a
|
|
|
|
field is represented by an ``<input type="checkbox">``, then that HTML will
|
|
|
|
include ``checked="checked"`` if appropriate::
|
|
|
|
|
|
|
|
>>> data = {'subject': 'hello',
|
|
|
|
... 'message': 'Hi there',
|
|
|
|
... 'sender': 'foo@example.com',
|
|
|
|
... 'cc_myself': True}
|
|
|
|
>>> f = ContactForm(data)
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f)
|
2008-08-23 22:25:40 +00:00
|
|
|
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" value="hello" /></td></tr>
|
|
|
|
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" value="Hi there" /></td></tr>
|
2013-01-28 13:12:56 +00:00
|
|
|
<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" value="foo@example.com" /></td></tr>
|
2008-08-23 22:25:40 +00:00
|
|
|
<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" checked="checked" /></td></tr>
|
|
|
|
|
|
|
|
This default output is a two-column HTML table, with a ``<tr>`` for each field.
|
|
|
|
Notice the following:
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* 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.
|
|
|
|
|
2013-01-28 13:12:56 +00:00
|
|
|
* Each field type has a default HTML representation. ``CharField`` is
|
|
|
|
represented by an ``<input type="text">`` and ``EmailField`` by an
|
|
|
|
``<input type="email">``.
|
2011-10-14 00:12:01 +00:00
|
|
|
``BooleanField`` is represented by an ``<input type="checkbox">``. Note
|
|
|
|
these are merely sensible defaults; you can specify which HTML to use for
|
|
|
|
a given field by using widgets, which we'll explain shortly.
|
|
|
|
|
|
|
|
* The HTML ``name`` for each tag is taken directly from its attribute name
|
|
|
|
in the ``ContactForm`` class.
|
|
|
|
|
|
|
|
* The text label for each field -- e.g. ``'Subject:'``, ``'Message:'`` and
|
|
|
|
``'Cc myself:'`` is generated from the field name by converting all
|
|
|
|
underscores to spaces and upper-casing the first letter. Again, note
|
|
|
|
these are merely sensible defaults; you can also specify labels manually.
|
|
|
|
|
|
|
|
* Each text label is surrounded in an HTML ``<label>`` tag, which points
|
|
|
|
to the appropriate form field via its ``id``. Its ``id``, in turn, is
|
|
|
|
generated by prepending ``'id_'`` to the field name. The ``id``
|
|
|
|
attributes and ``<label>`` tags are included in the output by default, to
|
|
|
|
follow best practices, but you can change that behavior.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
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()``
|
|
|
|
~~~~~~~~~~
|
|
|
|
|
2014-01-22 21:26:10 +00:00
|
|
|
.. method:: Form.as_p()
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
``as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>``
|
|
|
|
containing one field::
|
2009-12-25 20:51:30 +00:00
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
>>> f = ContactForm()
|
|
|
|
>>> f.as_p()
|
2014-03-22 20:30:49 +00:00
|
|
|
'<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>\n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>\n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p>\n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>'
|
2013-05-19 09:15:35 +00:00
|
|
|
>>> print(f.as_p())
|
|
|
|
<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>
|
|
|
|
<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>
|
|
|
|
<p><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></p>
|
|
|
|
<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
``as_ul()``
|
|
|
|
~~~~~~~~~~~
|
|
|
|
|
2014-01-22 21:26:10 +00:00
|
|
|
.. method:: Form.as_ul()
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
``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::
|
2009-12-25 20:51:30 +00:00
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
>>> f = ContactForm()
|
|
|
|
>>> f.as_ul()
|
2014-03-22 20:30:49 +00:00
|
|
|
'<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>\n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>\n<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></li>\n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>'
|
2013-05-19 09:15:35 +00:00
|
|
|
>>> print(f.as_ul())
|
|
|
|
<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>
|
|
|
|
<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>
|
|
|
|
<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></li>
|
|
|
|
<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
``as_table()``
|
|
|
|
~~~~~~~~~~~~~~
|
|
|
|
|
2014-01-22 21:26:10 +00:00
|
|
|
.. method:: Form.as_table()
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
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::
|
2009-12-25 20:51:30 +00:00
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
>>> f = ContactForm()
|
|
|
|
>>> f.as_table()
|
2014-03-22 20:30:49 +00:00
|
|
|
'<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>\n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" /></td></tr>\n<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>'
|
2013-05-19 09:15:35 +00:00
|
|
|
>>> print(f.as_table())
|
|
|
|
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
|
|
|
|
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
|
|
|
|
<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" /></td></tr>
|
|
|
|
<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2009-12-12 18:52:12 +00:00
|
|
|
Styling required or erroneous form rows
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
2013-01-01 13:12:42 +00:00
|
|
|
.. attribute:: Form.error_css_class
|
|
|
|
.. attribute:: Form.required_css_class
|
|
|
|
|
2009-12-12 18:52:12 +00:00
|
|
|
It's pretty common to style form rows and fields that are required or have
|
|
|
|
errors. For example, you might want to present required form rows in bold and
|
|
|
|
highlight errors in red.
|
|
|
|
|
|
|
|
The :class:`Form` class has a couple of hooks you can use to add ``class``
|
2011-03-22 23:16:22 +00:00
|
|
|
attributes to required rows or to rows with errors: simply set the
|
2009-12-12 18:52:12 +00:00
|
|
|
:attr:`Form.error_css_class` and/or :attr:`Form.required_css_class`
|
|
|
|
attributes::
|
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
from django.forms import Form
|
|
|
|
|
2009-12-12 18:52:12 +00:00
|
|
|
class ContactForm(Form):
|
|
|
|
error_css_class = 'error'
|
|
|
|
required_css_class = 'required'
|
2009-12-25 20:51:30 +00:00
|
|
|
|
2009-12-12 18:52:12 +00:00
|
|
|
# ... and the rest of your fields here
|
2009-12-25 20:51:30 +00:00
|
|
|
|
2009-12-12 18:52:12 +00:00
|
|
|
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)
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f.as_table())
|
2014-03-03 17:59:03 +00:00
|
|
|
<tr class="required"><th><label class="required" for="id_subject">Subject:</label> ...
|
|
|
|
<tr class="required"><th><label class="required" for="id_message">Message:</label> ...
|
|
|
|
<tr class="required error"><th><label class="required" for="id_sender">Sender:</label> ...
|
2009-12-12 18:52:12 +00:00
|
|
|
<tr><th><label for="id_cc_myself">Cc myself:<label> ...
|
2014-03-03 17:59:03 +00:00
|
|
|
>>> 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>
|
|
|
|
|
|
|
|
.. versionchanged:: 1.8
|
|
|
|
|
|
|
|
The ``required_css_class`` will also be added to the ``<label>`` tag as
|
|
|
|
seen above.
|
2009-12-12 18:52:12 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
.. _ref-forms-api-configuring-label:
|
|
|
|
|
2013-10-12 16:27:02 +00:00
|
|
|
Configuring form elements' HTML ``id`` attributes and ``<label>`` tags
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2013-10-12 16:27:02 +00:00
|
|
|
.. attribute:: Form.auto_id
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2013-10-12 16:27:02 +00:00
|
|
|
By default, the form rendering methods include:
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2013-10-12 16:27:02 +00:00
|
|
|
* 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.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
If ``auto_id`` is ``False``, then the form output will not include ``<label>``
|
|
|
|
tags nor ``id`` attributes::
|
|
|
|
|
|
|
|
>>> f = ContactForm(auto_id=False)
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f.as_table())
|
2008-08-23 22:25:40 +00:00
|
|
|
<tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /></td></tr>
|
|
|
|
<tr><th>Message:</th><td><input type="text" name="message" /></td></tr>
|
2013-01-28 13:12:56 +00:00
|
|
|
<tr><th>Sender:</th><td><input type="email" name="sender" /></td></tr>
|
2008-08-23 22:25:40 +00:00
|
|
|
<tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr>
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f.as_ul())
|
2008-08-23 22:25:40 +00:00
|
|
|
<li>Subject: <input type="text" name="subject" maxlength="100" /></li>
|
|
|
|
<li>Message: <input type="text" name="message" /></li>
|
2013-01-28 13:12:56 +00:00
|
|
|
<li>Sender: <input type="email" name="sender" /></li>
|
2008-08-23 22:25:40 +00:00
|
|
|
<li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f.as_p())
|
2008-08-23 22:25:40 +00:00
|
|
|
<p>Subject: <input type="text" name="subject" maxlength="100" /></p>
|
|
|
|
<p>Message: <input type="text" name="message" /></p>
|
2013-01-28 13:12:56 +00:00
|
|
|
<p>Sender: <input type="email" name="sender" /></p>
|
2008-08-23 22:25:40 +00:00
|
|
|
<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)
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f.as_table())
|
2008-08-23 22:25:40 +00:00
|
|
|
<tr><th><label for="subject">Subject:</label></th><td><input id="subject" type="text" name="subject" maxlength="100" /></td></tr>
|
|
|
|
<tr><th><label for="message">Message:</label></th><td><input type="text" name="message" id="message" /></td></tr>
|
2013-01-28 13:12:56 +00:00
|
|
|
<tr><th><label for="sender">Sender:</label></th><td><input type="email" name="sender" id="sender" /></td></tr>
|
2008-08-23 22:25:40 +00:00
|
|
|
<tr><th><label for="cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="cc_myself" /></td></tr>
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f.as_ul())
|
2008-08-23 22:25:40 +00:00
|
|
|
<li><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></li>
|
|
|
|
<li><label for="message">Message:</label> <input type="text" name="message" id="message" /></li>
|
2013-01-28 13:12:56 +00:00
|
|
|
<li><label for="sender">Sender:</label> <input type="email" name="sender" id="sender" /></li>
|
2008-08-23 22:25:40 +00:00
|
|
|
<li><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></li>
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f.as_p())
|
2008-08-23 22:25:40 +00:00
|
|
|
<p><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></p>
|
|
|
|
<p><label for="message">Message:</label> <input type="text" name="message" id="message" /></p>
|
2013-01-28 13:12:56 +00:00
|
|
|
<p><label for="sender">Sender:</label> <input type="email" name="sender" id="sender" /></p>
|
2008-08-23 22:25:40 +00:00
|
|
|
<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')
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f.as_table())
|
2008-08-23 22:25:40 +00:00
|
|
|
<tr><th><label for="id_for_subject">Subject:</label></th><td><input id="id_for_subject" type="text" name="subject" maxlength="100" /></td></tr>
|
|
|
|
<tr><th><label for="id_for_message">Message:</label></th><td><input type="text" name="message" id="id_for_message" /></td></tr>
|
2013-01-28 13:12:56 +00:00
|
|
|
<tr><th><label for="id_for_sender">Sender:</label></th><td><input type="email" name="sender" id="id_for_sender" /></td></tr>
|
2008-08-23 22:25:40 +00:00
|
|
|
<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>
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f.as_ul())
|
2008-08-23 22:25:40 +00:00
|
|
|
<li><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
|
|
|
|
<li><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></li>
|
2013-01-28 13:12:56 +00:00
|
|
|
<li><label for="id_for_sender">Sender:</label> <input type="email" name="sender" id="id_for_sender" /></li>
|
2008-08-23 22:25:40 +00:00
|
|
|
<li><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f.as_p())
|
2008-08-23 22:25:40 +00:00
|
|
|
<p><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></p>
|
|
|
|
<p><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></p>
|
2013-01-28 13:12:56 +00:00
|
|
|
<p><label for="id_for_sender">Sender:</label> <input type="email" name="sender" id="id_for_sender" /></p>
|
2008-08-23 22:25:40 +00:00
|
|
|
<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'``.
|
|
|
|
|
2012-06-08 13:32:35 +00:00
|
|
|
.. attribute:: Form.label_suffix
|
|
|
|
|
2013-07-13 09:43:14 +00:00
|
|
|
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
|
2013-10-12 16:27:02 +00:00
|
|
|
``label_suffix`` parameter::
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
>>> f = ContactForm(auto_id='id_for_%s', label_suffix='')
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f.as_ul())
|
2008-08-23 22:25:40 +00:00
|
|
|
<li><label for="id_for_subject">Subject</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
|
|
|
|
<li><label for="id_for_message">Message</label> <input type="text" name="message" id="id_for_message" /></li>
|
2013-01-28 13:12:56 +00:00
|
|
|
<li><label for="id_for_sender">Sender</label> <input type="email" name="sender" id="id_for_sender" /></li>
|
2008-08-23 22:25:40 +00:00
|
|
|
<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=' ->')
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f.as_ul())
|
2008-08-23 22:25:40 +00:00
|
|
|
<li><label for="id_for_subject">Subject -></label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
|
|
|
|
<li><label for="id_for_message">Message -></label> <input type="text" name="message" id="id_for_message" /></li>
|
2013-01-28 13:12:56 +00:00
|
|
|
<li><label for="id_for_sender">Sender -></label> <input type="email" name="sender" id="id_for_sender" /></li>
|
2008-08-23 22:25:40 +00:00
|
|
|
<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
|
2013-07-13 09:43:14 +00:00
|
|
|
label isn't a punctuation character (in English, those are ``.``, ``!``, ``?``
|
|
|
|
or ``:``).
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2014-04-29 08:07:57 +00:00
|
|
|
.. versionadded:: 1.8
|
|
|
|
|
|
|
|
Fields can also define their own :attr:`~django.forms.Field.label_suffix`.
|
|
|
|
This will take precedence over :attr:`Form.label_suffix
|
|
|
|
<django.forms.Form.label_suffix>`. The suffix can also be overridden at runtime
|
|
|
|
using the ``label_suffix`` parameter to
|
|
|
|
:meth:`~django.forms.BoundField.label_tag`.
|
2013-07-26 18:43:46 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
Notes on field ordering
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
In the ``as_p()``, ``as_ul()`` and ``as_table()`` shortcuts, the fields are
|
|
|
|
displayed in the order in which you define them in your form class. For
|
|
|
|
example, in the ``ContactForm`` example, the fields are defined in the order
|
|
|
|
``subject``, ``message``, ``sender``, ``cc_myself``. To reorder the HTML
|
|
|
|
output, just change the order in which those fields are listed in the class.
|
|
|
|
|
|
|
|
How errors are displayed
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
If you render a bound ``Form`` object, the act of rendering will automatically
|
|
|
|
run the form's validation if it hasn't already happened, and the HTML output
|
|
|
|
will include the validation errors as a ``<ul class="errorlist">`` near the
|
|
|
|
field. The particular positioning of the error messages depends on the output
|
|
|
|
method you're using::
|
|
|
|
|
|
|
|
>>> data = {'subject': '',
|
|
|
|
... 'message': 'Hi there',
|
2011-04-01 16:10:22 +00:00
|
|
|
... 'sender': 'invalid email address',
|
2008-08-23 22:25:40 +00:00
|
|
|
... 'cc_myself': True}
|
|
|
|
>>> f = ContactForm(data, auto_id=False)
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f.as_table())
|
2008-08-23 22:25:40 +00:00
|
|
|
<tr><th>Subject:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" /></td></tr>
|
|
|
|
<tr><th>Message:</th><td><input type="text" name="message" value="Hi there" /></td></tr>
|
2013-01-28 13:12:56 +00:00
|
|
|
<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" /></td></tr>
|
2008-08-23 22:25:40 +00:00
|
|
|
<tr><th>Cc myself:</th><td><input checked="checked" type="checkbox" name="cc_myself" /></td></tr>
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f.as_ul())
|
2008-08-23 22:25:40 +00:00
|
|
|
<li><ul class="errorlist"><li>This field is required.</li></ul>Subject: <input type="text" name="subject" maxlength="100" /></li>
|
|
|
|
<li>Message: <input type="text" name="message" value="Hi there" /></li>
|
2013-01-28 13:12:56 +00:00
|
|
|
<li><ul class="errorlist"><li>Enter a valid email address.</li></ul>Sender: <input type="email" name="sender" value="invalid email address" /></li>
|
2008-08-23 22:25:40 +00:00
|
|
|
<li>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></li>
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f.as_p())
|
2008-08-23 22:25:40 +00:00
|
|
|
<p><ul class="errorlist"><li>This field is required.</li></ul></p>
|
|
|
|
<p>Subject: <input type="text" name="subject" maxlength="100" /></p>
|
|
|
|
<p>Message: <input type="text" name="message" value="Hi there" /></p>
|
2012-09-26 12:14:51 +00:00
|
|
|
<p><ul class="errorlist"><li>Enter a valid email address.</li></ul></p>
|
2013-01-28 13:12:56 +00:00
|
|
|
<p>Sender: <input type="email" name="sender" value="invalid email address" /></p>
|
2008-08-23 22:25:40 +00:00
|
|
|
<p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p>
|
|
|
|
|
|
|
|
Customizing the error list format
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
2013-09-16 16:52:05 +00:00
|
|
|
By default, forms use ``django.forms.utils.ErrorList`` to format validation
|
2008-08-23 22:25:40 +00:00
|
|
|
errors. If you'd like to use an alternate class for displaying errors, you can
|
2014-02-09 11:38:13 +00:00
|
|
|
pass that in at construction time (replace ``__str__`` by ``__unicode__`` on
|
|
|
|
Python 2)::
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2013-09-16 16:52:05 +00:00
|
|
|
>>> from django.forms.utils import ErrorList
|
2008-08-23 22:25:40 +00:00
|
|
|
>>> class DivErrorList(ErrorList):
|
2014-02-09 11:38:13 +00:00
|
|
|
... def __str__(self): # __unicode__ on Python 2
|
2008-08-23 22:25:40 +00:00
|
|
|
... return self.as_divs()
|
|
|
|
... def as_divs(self):
|
2014-02-09 11:38:13 +00:00
|
|
|
... if not self: return ''
|
|
|
|
... return '<div class="errorlist">%s</div>' % ''.join(['<div class="error">%s</div>' % e for e in self])
|
2008-08-23 22:25:40 +00:00
|
|
|
>>> f = ContactForm(data, auto_id=False, error_class=DivErrorList)
|
|
|
|
>>> f.as_p()
|
|
|
|
<div class="errorlist"><div class="error">This field is required.</div></div>
|
|
|
|
<p>Subject: <input type="text" name="subject" maxlength="100" /></p>
|
|
|
|
<p>Message: <input type="text" name="message" value="Hi there" /></p>
|
2012-09-26 12:14:51 +00:00
|
|
|
<div class="errorlist"><div class="error">Enter a valid email address.</div></div>
|
2013-01-28 13:12:56 +00:00
|
|
|
<p>Sender: <input type="email" name="sender" value="invalid email address" /></p>
|
2008-08-23 22:25:40 +00:00
|
|
|
<p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p>
|
|
|
|
|
2013-09-16 16:52:05 +00:00
|
|
|
.. versionchanged:: 1.7
|
|
|
|
|
|
|
|
``django.forms.util`` was renamed to ``django.forms.utils``.
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
More granular output
|
|
|
|
~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
The ``as_p()``, ``as_ul()`` and ``as_table()`` methods are simply shortcuts for
|
|
|
|
lazy developers -- they're not the only way a form object can be displayed.
|
|
|
|
|
2010-11-28 02:50:31 +00:00
|
|
|
.. class:: BoundField
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2010-11-28 02:50:31 +00:00
|
|
|
Used to display HTML or access attributes for a single field of a
|
|
|
|
:class:`Form` instance.
|
2012-08-04 12:17:02 +00:00
|
|
|
|
2014-02-09 11:38:13 +00:00
|
|
|
The ``__str__()`` (``__unicode__`` on Python 2) method of this
|
|
|
|
object displays the HTML for this field.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2010-11-28 02:50:31 +00:00
|
|
|
To retrieve a single ``BoundField``, use dictionary lookup syntax on your form
|
|
|
|
using the field's name as the key::
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2013-01-01 13:12:42 +00:00
|
|
|
>>> form = ContactForm()
|
|
|
|
>>> print(form['subject'])
|
|
|
|
<input id="id_subject" type="text" name="subject" maxlength="100" />
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2010-11-28 02:50:31 +00:00
|
|
|
To retrieve all ``BoundField`` objects, iterate the form::
|
2008-09-15 00:07:13 +00:00
|
|
|
|
2013-01-01 13:12:42 +00:00
|
|
|
>>> form = ContactForm()
|
|
|
|
>>> for boundfield in form: print(boundfield)
|
|
|
|
<input id="id_subject" type="text" name="subject" maxlength="100" />
|
|
|
|
<input type="text" name="message" id="id_message" />
|
2013-01-28 13:12:56 +00:00
|
|
|
<input type="email" name="sender" id="id_sender" />
|
2013-01-01 13:12:42 +00:00
|
|
|
<input type="checkbox" name="cc_myself" id="id_cc_myself" />
|
2008-09-15 00:07:13 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
The field-specific output honors the form object's ``auto_id`` setting::
|
|
|
|
|
|
|
|
>>> f = ContactForm(auto_id=False)
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f['message'])
|
2008-08-23 22:25:40 +00:00
|
|
|
<input type="text" name="message" />
|
|
|
|
>>> f = ContactForm(auto_id='id_%s')
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f['message'])
|
2008-08-23 22:25:40 +00:00
|
|
|
<input type="text" name="message" id="id_message" />
|
|
|
|
|
2010-11-28 02:50:31 +00:00
|
|
|
For a field's list of errors, access the field's ``errors`` attribute.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2010-11-28 02:50:31 +00:00
|
|
|
.. attribute:: BoundField.errors
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
A list-like object that is displayed as an HTML ``<ul class="errorlist">``
|
|
|
|
when printed::
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
>>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''}
|
|
|
|
>>> f = ContactForm(data, auto_id=False)
|
|
|
|
>>> print(f['message'])
|
|
|
|
<input type="text" name="message" />
|
|
|
|
>>> f['message'].errors
|
2014-03-22 20:30:49 +00:00
|
|
|
['This field is required.']
|
2013-05-19 09:15:35 +00:00
|
|
|
>>> print(f['message'].errors)
|
|
|
|
<ul class="errorlist"><li>This field is required.</li></ul>
|
|
|
|
>>> f['subject'].errors
|
|
|
|
[]
|
|
|
|
>>> print(f['subject'].errors)
|
2010-11-28 02:50:31 +00:00
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
>>> str(f['subject'].errors)
|
|
|
|
''
|
2010-11-28 02:50:31 +00:00
|
|
|
|
2013-07-26 18:43:46 +00:00
|
|
|
.. method:: BoundField.label_tag(contents=None, attrs=None, label_suffix=None)
|
2013-04-12 08:13:38 +00:00
|
|
|
|
|
|
|
To separately render the label tag of a form field, you can call its
|
|
|
|
``label_tag`` method::
|
|
|
|
|
|
|
|
>>> f = ContactForm(data)
|
|
|
|
>>> print(f['message'].label_tag())
|
2012-06-08 13:32:35 +00:00
|
|
|
<label for="id_message">Message:</label>
|
2013-04-12 08:13:38 +00:00
|
|
|
|
|
|
|
Optionally, you can provide the ``contents`` parameter which will replace the
|
|
|
|
auto-generated label tag. An optional ``attrs`` dictionary may contain
|
|
|
|
additional attributes for the ``<label>`` tag.
|
|
|
|
|
2014-03-24 15:42:56 +00:00
|
|
|
The HTML that's generated includes the form's
|
2014-04-29 08:07:57 +00:00
|
|
|
:attr:`~django.forms.Form.label_suffix` (a colon, by default) or, if set, the
|
|
|
|
current field's :attr:`~django.forms.Field.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``.
|
2013-07-26 18:43:46 +00:00
|
|
|
|
2014-03-03 17:59:03 +00:00
|
|
|
.. versionchanged:: 1.8
|
|
|
|
|
|
|
|
The label includes :attr:`~Form.required_css_class` if applicable.
|
|
|
|
|
2010-11-28 02:50:31 +00:00
|
|
|
.. method:: BoundField.css_classes()
|
|
|
|
|
2010-03-08 03:18:22 +00:00
|
|
|
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::
|
|
|
|
|
2013-01-01 13:12:42 +00:00
|
|
|
>>> f = ContactForm(data)
|
|
|
|
>>> f['message'].css_classes()
|
|
|
|
'required'
|
2010-03-08 03:18:22 +00:00
|
|
|
|
|
|
|
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::
|
|
|
|
|
2013-01-01 13:12:42 +00:00
|
|
|
>>> f = ContactForm(data)
|
|
|
|
>>> f['message'].css_classes('foo bar')
|
|
|
|
'foo bar required'
|
2010-03-08 03:18:22 +00:00
|
|
|
|
2011-03-07 22:55:16 +00:00
|
|
|
.. method:: BoundField.value()
|
2010-11-28 02:50:31 +00:00
|
|
|
|
|
|
|
Use this method to render the raw value of this field as it would be rendered
|
|
|
|
by a ``Widget``::
|
|
|
|
|
|
|
|
>>> initial = {'subject': 'welcome'}
|
|
|
|
>>> unbound_form = ContactForm(initial=initial)
|
|
|
|
>>> bound_form = ContactForm(data, initial=initial)
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(unbound_form['subject'].value())
|
2010-11-28 02:50:31 +00:00
|
|
|
welcome
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(bound_form['subject'].value())
|
2010-11-28 02:50:31 +00:00
|
|
|
hi
|
|
|
|
|
2013-06-06 18:15:26 +00:00
|
|
|
.. attribute:: 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
|
|
|
|
:meth:`~BoundField.label_tag` will do this for you):
|
|
|
|
|
|
|
|
.. code-block:: html+django
|
|
|
|
|
|
|
|
<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
|
|
|
|
:attr:`~django.forms.Widget.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:
|
|
|
|
|
|
|
|
.. code-block:: html
|
|
|
|
|
|
|
|
<label for="myFIELD">...</label><input id="myFIELD" type="text" name="my_field" />
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
.. _binding-uploaded-files:
|
|
|
|
|
|
|
|
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': 'foo@example.com',
|
|
|
|
... 'cc_myself': True}
|
|
|
|
>>> file_data = {'mugshot': SimpleUploadedFile('face.jpg', <file data>)}
|
|
|
|
>>> f = ContactFormWithMugshot(data, file_data)
|
|
|
|
|
|
|
|
In practice, you will usually specify ``request.FILES`` as the source
|
|
|
|
of file data (just like you use ``request.POST`` as the source of
|
|
|
|
form data)::
|
|
|
|
|
|
|
|
# Bound form with an image field, data from the request
|
|
|
|
>>> f = ContactFormWithMugshot(request.POST, request.FILES)
|
|
|
|
|
|
|
|
Constructing an unbound form is the same as always -- just omit both
|
|
|
|
form data *and* file data::
|
|
|
|
|
|
|
|
# Unbound form with a image field
|
|
|
|
>>> f = ContactFormWithMugshot()
|
|
|
|
|
|
|
|
Testing for multipart forms
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
2014-01-22 21:26:10 +00:00
|
|
|
.. method:: Form.is_multipart()
|
2013-01-23 09:42:34 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
If you're writing reusable views or templates, you may not know ahead of time
|
|
|
|
whether your form is a multipart form or not. The ``is_multipart()`` method
|
|
|
|
tells you whether the form requires multipart encoding for submission::
|
|
|
|
|
|
|
|
>>> f = ContactFormWithMugshot()
|
|
|
|
>>> f.is_multipart()
|
|
|
|
True
|
|
|
|
|
|
|
|
Here's an example of how you might use this in a template::
|
|
|
|
|
|
|
|
{% if form.is_multipart %}
|
|
|
|
<form enctype="multipart/form-data" method="post" action="/foo/">
|
|
|
|
{% else %}
|
|
|
|
<form method="post" action="/foo/">
|
|
|
|
{% endif %}
|
|
|
|
{{ form }}
|
|
|
|
</form>
|
|
|
|
|
|
|
|
Subclassing forms
|
|
|
|
-----------------
|
|
|
|
|
|
|
|
If you have multiple ``Form`` classes that share fields, you can use
|
|
|
|
subclassing to remove redundancy.
|
|
|
|
|
|
|
|
When you subclass a custom ``Form`` class, the resulting subclass will
|
|
|
|
include all fields of the parent class(es), followed by the fields you define
|
|
|
|
in the subclass.
|
|
|
|
|
|
|
|
In this example, ``ContactFormWithPriority`` contains all the fields from
|
|
|
|
``ContactForm``, plus an additional field, ``priority``. The ``ContactForm``
|
|
|
|
fields are ordered first::
|
|
|
|
|
|
|
|
>>> class ContactFormWithPriority(ContactForm):
|
|
|
|
... priority = forms.CharField()
|
|
|
|
>>> f = ContactFormWithPriority(auto_id=False)
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(f.as_ul())
|
2008-08-23 22:25:40 +00:00
|
|
|
<li>Subject: <input type="text" name="subject" maxlength="100" /></li>
|
|
|
|
<li>Message: <input type="text" name="message" /></li>
|
2013-01-28 13:12:56 +00:00
|
|
|
<li>Sender: <input type="email" name="sender" /></li>
|
2008-08-23 22:25:40 +00:00
|
|
|
<li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
|
|
|
|
<li>Priority: <input type="text" name="priority" /></li>
|
|
|
|
|
|
|
|
It's possible to subclass multiple forms, treating forms as "mix-ins." In this
|
|
|
|
example, ``BeatleForm`` subclasses both ``PersonForm`` and ``InstrumentForm``
|
|
|
|
(in that order), and its field list includes the fields from the parent
|
|
|
|
classes::
|
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
>>> from django.forms import Form
|
2008-08-23 22:25:40 +00:00
|
|
|
>>> class PersonForm(Form):
|
|
|
|
... first_name = CharField()
|
|
|
|
... last_name = CharField()
|
|
|
|
>>> class InstrumentForm(Form):
|
|
|
|
... instrument = CharField()
|
|
|
|
>>> class BeatleForm(PersonForm, InstrumentForm):
|
|
|
|
... haircut_type = CharField()
|
|
|
|
>>> b = BeatleForm(auto_id=False)
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(b.as_ul())
|
2008-08-23 22:25:40 +00:00
|
|
|
<li>First name: <input type="text" name="first_name" /></li>
|
|
|
|
<li>Last name: <input type="text" name="last_name" /></li>
|
|
|
|
<li>Instrument: <input type="text" name="instrument" /></li>
|
|
|
|
<li>Haircut type: <input type="text" name="haircut_type" /></li>
|
|
|
|
|
2013-10-14 15:42:33 +00:00
|
|
|
.. versionadded:: 1.7
|
|
|
|
|
2014-05-24 09:52:18 +00:00
|
|
|
* It's possible to declaratively remove a ``Field`` inherited from a parent
|
|
|
|
class by setting the name to be ``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
|
|
|
|
|
|
|
|
>>> ChildForm().fields.keys()
|
|
|
|
... ['age']
|
2013-10-14 15:42:33 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
.. _form-prefix:
|
|
|
|
|
|
|
|
Prefixes for forms
|
|
|
|
------------------
|
|
|
|
|
|
|
|
.. attribute:: Form.prefix
|
|
|
|
|
|
|
|
You can put several Django forms inside one ``<form>`` tag. To give each
|
|
|
|
``Form`` its own namespace, use the ``prefix`` keyword argument::
|
|
|
|
|
|
|
|
>>> mother = PersonForm(prefix="mother")
|
|
|
|
>>> father = PersonForm(prefix="father")
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(mother.as_ul())
|
2008-08-23 22:25:40 +00:00
|
|
|
<li><label for="id_mother-first_name">First name:</label> <input type="text" name="mother-first_name" id="id_mother-first_name" /></li>
|
|
|
|
<li><label for="id_mother-last_name">Last name:</label> <input type="text" name="mother-last_name" id="id_mother-last_name" /></li>
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(father.as_ul())
|
2008-08-23 22:25:40 +00:00
|
|
|
<li><label for="id_father-first_name">First name:</label> <input type="text" name="father-first_name" id="id_father-first_name" /></li>
|
|
|
|
<li><label for="id_father-last_name">Last name:</label> <input type="text" name="father-last_name" id="id_father-last_name" /></li>
|