summaryrefslogtreecommitdiff
path: root/docs/ref/forms
diff options
context:
space:
mode:
Diffstat (limited to 'docs/ref/forms')
-rw-r--r--docs/ref/forms/api.txt46
-rw-r--r--docs/ref/forms/fields.txt459
-rw-r--r--docs/ref/forms/validation.txt114
-rw-r--r--docs/ref/forms/widgets.txt131
4 files changed, 367 insertions, 383 deletions
diff --git a/docs/ref/forms/api.txt b/docs/ref/forms/api.txt
index 070f9ef19a..86b6bb453e 100644
--- a/docs/ref/forms/api.txt
+++ b/docs/ref/forms/api.txt
@@ -19,11 +19,11 @@ 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 **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.
+* 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
@@ -292,29 +292,29 @@ include ``checked="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 ``<input type="submit">`` tag. It's your job to do that.
+* For flexibility, the output does *not* include the ``<table>`` and
+ ``</table>`` tags, nor does it include the ``<form>`` and ``</form>``
+ tags or an ``<input type="submit">`` tag. It's your job to do that.
- * Each field type has a default HTML representation. ``CharField`` and
- ``EmailField`` are represented by an ``<input type="text">``.
- ``BooleanField`` is represented by an ``<input type="checkbox">``. Note
- these are merely sensible defaults; you can specify which HTML to use for
- a given field by using widgets, which we'll explain shortly.
+* Each field type has a default HTML representation. ``CharField`` and
+ ``EmailField`` are represented by an ``<input type="text">``.
+ ``BooleanField`` is represented by an ``<input type="checkbox">``. Note
+ these are merely sensible defaults; you can specify which HTML to use for
+ a given field by using widgets, which we'll explain shortly.
- * The HTML ``name`` for each tag is taken directly from its attribute name
- in the ``ContactForm`` class.
+* The 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.
+* 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.
+* Each text label is surrounded in an HTML ``<label>`` tag, which points
+ to the appropriate form field via its ``id``. Its ``id``, in turn, is
+ generated by prepending ``'id_'`` to the field name. The ``id``
+ attributes and ``<label>`` tags are included in the output by default, to
+ follow best practices, but you can change that behavior.
Although ``<table>`` output is the default output style when you ``print`` a
form, other output styles are available. Each style is available as a method on
diff --git a/docs/ref/forms/fields.txt b/docs/ref/forms/fields.txt
index 54fdec6d38..fc8665b252 100644
--- a/docs/ref/forms/fields.txt
+++ b/docs/ref/forms/fields.txt
@@ -302,13 +302,13 @@ For each field, we describe the default widget used if you don't specify
the field has ``required=True``.
* Error message keys: ``required``
-.. note::
+ .. 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``.
+ 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``
~~~~~~~~~~~~~
@@ -322,10 +322,10 @@ For each field, we describe the default widget used if you don't specify
Otherwise, all inputs are valid.
* Error message keys: ``required``, ``max_length``, ``min_length``
-Has two optional arguments for validation:
+ Has two optional arguments for validation:
-.. attribute:: CharField.max_length
-.. attribute:: CharField.min_length
+ .. attribute:: max_length
+ .. attribute:: min_length
If provided, these arguments ensure that the string is at most or at least
the given length.
@@ -341,25 +341,25 @@ Has two optional arguments for validation:
* 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.
+ The ``invalid_choice`` error message may contain ``%(value)s``, which will be
+ replaced with the selected choice.
-Takes one extra required argument:
+ Takes one extra required argument:
-.. attribute:: ChoiceField.choices
+ .. attribute:: choices
- An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this
- field. This argument accepts the same formats as the ``choices`` argument
- to a model field. See the :ref:`model field reference documentation on
- choices <field-choices>` for more details.
+ An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this
+ field. This argument accepts the same formats as the ``choices`` argument
+ to a model field. See the :ref:`model field reference documentation on
+ choices <field-choices>` for more details.
``TypedChoiceField``
~~~~~~~~~~~~~~~~~~~~
.. class:: TypedChoiceField(**kwargs)
-Just like a :class:`ChoiceField`, except :class:`TypedChoiceField` takes two
-extra arguments, ``coerce`` and ``empty_value``.
+ Just like a :class:`ChoiceField`, except :class:`TypedChoiceField` takes two
+ extra arguments, ``coerce`` and ``empty_value``.
* Default widget: ``Select``
* Empty value: Whatever you've given as ``empty_value``
@@ -368,20 +368,20 @@ extra arguments, ``coerce`` and ``empty_value``.
coerced.
* Error message keys: ``required``, ``invalid_choice``
-Takes extra arguments:
+ Takes extra arguments:
-.. attribute:: TypedChoiceField.coerce
+ .. attribute:: 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.
+ 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.
-.. attribute:: TypedChoiceField.empty_value
+ .. attribute:: 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.
+ 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``
~~~~~~~~~~~~~
@@ -395,20 +395,20 @@ Takes extra arguments:
``datetime.datetime`` or string formatted in a particular date format.
* Error message keys: ``required``, ``invalid``
-Takes one optional argument:
+ Takes one optional argument:
-.. attribute:: DateField.input_formats
+ .. attribute:: input_formats
- A list of formats used to attempt to convert a string to a valid
- ``datetime.date`` object.
+ 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::
+ 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'
- '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'
- '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'
- '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006'
- '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'
+ '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
+ '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'
+ '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'
+ '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006'
+ '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'
``DateTimeField``
~~~~~~~~~~~~~~~~~
@@ -422,24 +422,24 @@ If no ``input_formats`` argument is provided, the default input formats are::
``datetime.date`` or string formatted in a particular datetime format.
* Error message keys: ``required``, ``invalid``
-Takes one optional argument:
+ Takes one optional argument:
-.. attribute:: DateTimeField.input_formats
+ .. attribute:: input_formats
- A list of formats used to attempt to convert a string to a valid
- ``datetime.datetime`` object.
+ 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::
+ If no ``input_formats`` argument is provided, the default input formats are::
- '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
- '%Y-%m-%d %H:%M', # '2006-10-25 14:30'
- '%Y-%m-%d', # '2006-10-25'
- '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
- '%m/%d/%Y %H:%M', # '10/25/2006 14:30'
- '%m/%d/%Y', # '10/25/2006'
- '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
- '%m/%d/%y %H:%M', # '10/25/06 14:30'
- '%m/%d/%y', # '10/25/06'
+ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
+ '%Y-%m-%d %H:%M', # '2006-10-25 14:30'
+ '%Y-%m-%d', # '2006-10-25'
+ '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
+ '%m/%d/%Y %H:%M', # '10/25/2006 14:30'
+ '%m/%d/%Y', # '10/25/2006'
+ '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
+ '%m/%d/%y %H:%M', # '10/25/06 14:30'
+ '%m/%d/%y', # '10/25/06'
``DecimalField``
~~~~~~~~~~~~~~~~
@@ -455,26 +455,26 @@ If no ``input_formats`` argument is provided, the default input formats are::
``min_value``, ``max_digits``, ``max_decimal_places``,
``max_whole_digits``
-The ``max_value`` and ``min_value`` error messages may contain
-``%(limit_value)s``, which will be substituted by the appropriate limit.
+ The ``max_value`` and ``min_value`` error messages may contain
+ ``%(limit_value)s``, which will be substituted by the appropriate limit.
-Takes four optional arguments:
+ Takes four optional arguments:
-.. attribute:: DecimalField.max_value
-.. attribute:: DecimalField.min_value
+ .. attribute:: max_value
+ .. attribute:: min_value
- These control the range of values permitted in the field, and should be
- given as ``decimal.Decimal`` values.
+ These control the range of values permitted in the field, and should be
+ given as ``decimal.Decimal`` values.
-.. attribute:: DecimalField.max_digits
+ .. attribute:: 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.
+ The maximum number of digits (those before the decimal point plus those
+ after the decimal point, with leading zeros stripped) permitted in the
+ value.
-.. attribute:: DecimalField.decimal_places
+ .. attribute:: decimal_places
- The maximum number of decimal places permitted.
+ The maximum number of decimal places permitted.
``EmailField``
~~~~~~~~~~~~~~
@@ -488,9 +488,9 @@ Takes four optional arguments:
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.
+ 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.
.. versionchanged:: 1.2
The EmailField previously did not recognize email addresses as valid that
@@ -510,20 +510,20 @@ given length.
* 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.
+ 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 :doc:`file uploads
-documentation </topics/http/file-uploads>`.
+ To learn more about the ``UploadedFile`` object, see the :doc:`file uploads
+ documentation </topics/http/file-uploads>`.
-When you use a ``FileField`` in a form, you must also remember to
-:ref:`bind the file data to the form <binding-uploaded-files>`.
+ When you use a ``FileField`` in a form, you must also remember to
+ :ref:`bind the file data to the form <binding-uploaded-files>`.
-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.
+ 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``
~~~~~~~~~~~~~~~~~
@@ -536,28 +536,30 @@ length and ``%(length)d`` will be replaced with the current filename length.
* Validates that the selected choice exists in the list of choices.
* Error message keys: ``required``, ``invalid_choice``
-The field allows choosing from files inside a certain directory. It takes three
-extra arguments; only ``path`` is required:
+ The field allows choosing from files inside a certain directory. It takes three
+ extra arguments; only ``path`` is required:
-.. attribute:: FilePathField.path
+ .. attribute:: path
- The absolute path to the directory whose contents you want listed. This
- directory must exist.
+ The absolute path to the directory whose contents you want listed. This
+ directory must exist.
-.. attribute:: FilePathField.recursive
+ .. attribute:: 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.
+ 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.
-.. attribute:: FilePathField.match
+ .. attribute:: match
- A regular expression pattern; only files with names matching this expression
- will be allowed as choices.
+ A regular expression pattern; only files with names matching this expression
+ will be allowed as choices.
``FloatField``
~~~~~~~~~~~~~~
+.. class:: FloatField(**kwargs)
+
* Default widget: ``TextInput``
* Empty value: ``None``
* Normalizes to: A Python float.
@@ -566,8 +568,8 @@ extra arguments; only ``path`` is required:
* 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.
+ Takes two optional arguments for validation, ``max_value`` and ``min_value``.
+ These control the range of values permitted in the field.
``ImageField``
~~~~~~~~~~~~~~
@@ -583,10 +585,10 @@ These control the range of values permitted in the field.
* Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,
``invalid_image``
-Using an ImageField requires that the `Python Imaging Library`_ is installed.
+ Using an ImageField requires that the `Python Imaging Library`_ is installed.
-When you use an ``ImageField`` on a form, you must also remember to
-:ref:`bind the file data to the form <binding-uploaded-files>`.
+ When you use an ``ImageField`` on a form, you must also remember to
+ :ref:`bind the file data to the form <binding-uploaded-files>`.
.. _Python Imaging Library: http://www.pythonware.com/products/pil/
@@ -603,13 +605,13 @@ When you use an ``ImageField`` on a form, you must also remember to
* 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.
+ 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:
+ Takes two optional arguments for validation:
-.. attribute:: IntegerField.max_value
-.. attribute:: IntegerField.min_value
+ .. attribute:: max_value
+ .. attribute:: min_value
These control the range of values permitted in the field.
@@ -628,11 +630,11 @@ Takes two optional arguments for validation:
``GenericIPAddressField``
~~~~~~~~~~~~~~~~~~~~~~~~~
-.. class:: GenericIPAddressField(**kwargs)
-
.. versionadded:: 1.4
-A field containing either an IPv4 or an IPv6 address.
+.. class:: GenericIPAddressField(**kwargs)
+
+ A field containing either an IPv4 or an IPv6 address.
* Default widget: ``TextInput``
* Empty value: ``''`` (an empty string)
@@ -641,26 +643,26 @@ A field containing either an IPv4 or an IPv6 address.
* 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.
+ 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:
+ Takes two optional arguments:
-.. attribute:: GenericIPAddressField.protocol
+ .. attribute:: protocol
- Limits valid inputs to the specified protocol.
- Accepted values are ``both`` (default), ``IPv4``
- or ``IPv6``. Matching is case insensitive.
+ Limits valid inputs to the specified protocol.
+ Accepted values are ``both`` (default), ``IPv4``
+ or ``IPv6``. Matching is case insensitive.
-.. attribute:: GenericIPAddressField.unpack_ipv4
+ .. attribute:: 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'``.
+ 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``
~~~~~~~~~~~~~~~~~~~~~~~
@@ -674,20 +676,20 @@ Takes two optional arguments:
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.
+ 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``.
+ Takes one extra required argument, ``choices``, as for ``ChoiceField``.
``TypedMultipleChoiceField``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-.. class:: TypedMultipleChoiceField(**kwargs)
-
.. versionadded:: 1.3
-Just like a :class:`MultipleChoiceField`, except :class:`TypedMultipleChoiceField`
-takes two extra arguments, ``coerce`` and ``empty_value``.
+.. class:: TypedMultipleChoiceField(**kwargs)
+
+ Just like a :class:`MultipleChoiceField`, except :class:`TypedMultipleChoiceField`
+ takes two extra arguments, ``coerce`` and ``empty_value``.
* Default widget: ``SelectMultiple``
* Empty value: Whatever you've given as ``empty_value``
@@ -697,10 +699,10 @@ takes two extra arguments, ``coerce`` and ``empty_value``.
coerced.
* Error message keys: ``required``, ``invalid_choice``
-The ``invalid_choice`` error message may contain ``%(value)s``, which will be
-replaced with the selected 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``.
+ Takes two extra arguments, ``coerce`` and ``empty_value``, as for ``TypedChoiceField``.
``NullBooleanField``
~~~~~~~~~~~~~~~~~~~~
@@ -724,20 +726,20 @@ Takes two extra arguments, ``coerce`` and ``empty_value``, as for ``TypedChoiceF
expression.
* Error message keys: ``required``, ``invalid``
-Takes one required argument:
+ Takes one required argument:
-.. attribute:: RegexField.regex
+ .. attribute:: regex
- A regular expression specified either as a string or a compiled regular
- expression object.
+ A regular expression specified either as a string or a compiled regular
+ expression object.
-Also takes ``max_length`` and ``min_length``, which work just as they do for
-``CharField``.
+ Also takes ``max_length`` and ``min_length``, which work just as they do for
+ ``CharField``.
-The optional argument ``error_message`` is also accepted for backwards
-compatibility. The preferred way to provide an error message is to use the
-``error_messages`` argument, passing a dictionary with ``'invalid'`` as a key
-and the error message as the value.
+ The optional argument ``error_message`` is also accepted for backwards
+ compatibility. The preferred way to provide an error message is to use the
+ ``error_messages`` argument, passing a dictionary with ``'invalid'`` as a key
+ and the error message as the value.
``SlugField``
~~~~~~~~~~~~~
@@ -751,8 +753,8 @@ and the error message as the value.
underscores, and hyphens.
* Error messages: ``required``, ``invalid``
-This field is intended for use in representing a model
-:class:`~django.db.models.SlugField` in forms.
+ This field is intended for use in representing a model
+ :class:`~django.db.models.SlugField` in forms.
``TimeField``
~~~~~~~~~~~~~
@@ -766,17 +768,17 @@ This field is intended for use in representing a model
formatted in a particular time format.
* Error message keys: ``required``, ``invalid``
-Takes one optional argument:
+ Takes one optional argument:
-.. attribute:: TimeField.input_formats
+ .. attribute:: input_formats
- A list of formats used to attempt to convert a string to a valid
- ``datetime.time`` object.
+ 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::
+ If no ``input_formats`` argument is provided, the default input formats are::
- '%H:%M:%S', # '14:30:59'
- '%H:%M', # '14:30'
+ '%H:%M:%S', # '14:30:59'
+ '%H:%M', # '14:30'
``URLField``
~~~~~~~~~~~~
@@ -789,27 +791,26 @@ If no ``input_formats`` argument is provided, the default input formats are::
* Validates that the given value is a valid URL.
* Error message keys: ``required``, ``invalid``, ``invalid_link``
-Takes the following optional arguments:
-
-.. attribute:: URLField.max_length
-.. attribute:: URLField.min_length
+ Takes the following optional arguments:
- Same as ``CharField.max_length`` and ``CharField.min_length``.
+ .. attribute:: max_length
+ .. attribute:: min_length
-.. attribute:: URLField.verify_exists
+ These are the same as ``CharField.max_length`` and ``CharField.min_length``.
- If ``True``, the validator will attempt to load the given URL, raising
- ``ValidationError`` if the page gives a 404. Defaults to ``False``.
+ .. attribute:: verify_exists
-.. deprecated:: 1.4
+ If ``True``, the validator will attempt to load the given URL, raising
+ ``ValidationError`` if the page gives a 404. Defaults to ``False``.
- ``verify_exists`` was deprecated for security reasons and will be removed in
- Django 1.5. This deprecation also removes ``validator_user_agent``.
+ .. deprecated:: 1.4
+ ``verify_exists`` was deprecated for security reasons and will be removed in
+ Django 1.5. This deprecation also removes ``validator_user_agent``.
-.. attribute:: URLField.validator_user_agent
+ .. attribute:: validator_user_agent
- String used as the user-agent used when checking for a URL's existence.
- Defaults to the value of the :setting:`URL_VALIDATOR_USER_AGENT` setting.
+ String used as the user-agent used when checking for a URL's existence.
+ Defaults to the value of the :setting:`URL_VALIDATOR_USER_AGENT` setting.
.. versionchanged:: 1.2
The URLField previously did not recognize URLs as valid that contained an IDN
@@ -832,20 +833,20 @@ Slightly complex built-in ``Field`` classes
as an argument to the ``ComboField``.
* Error message keys: ``required``, ``invalid``
-Takes one extra required argument:
+ Takes one extra required argument:
-.. attribute:: ComboField.fields
+ .. attribute:: fields
- The list of fields that should be used to validate the field's value (in
- the order in which they are provided).
+ The list of fields that should be used to validate the field's value (in
+ the order in which they are provided).
- >>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
- >>> f.clean('test@example.com')
- u'test@example.com'
- >>> f.clean('longemailaddress@example.com')
- Traceback (most recent call last):
- ...
- ValidationError: [u'Ensure this value has at most 20 characters (it has 28).']
+ >>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
+ >>> f.clean('test@example.com')
+ u'test@example.com'
+ >>> f.clean('longemailaddress@example.com')
+ Traceback (most recent call last):
+ ...
+ ValidationError: [u'Ensure this value has at most 20 characters (it has 28).']
``MultiValueField``
~~~~~~~~~~~~~~~~~~~
@@ -866,15 +867,15 @@ Takes one extra required argument:
:class:`SplitDateTimeField` is a subclass which combines a time field and
a date field into a datetime object.
-Takes one extra required argument:
+ Takes one extra required argument:
-.. attribute:: MultiValueField.fields
+ .. attribute:: fields
- A list of fields which are cleaned into a single field. Each value in
- ``clean`` 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 "compressed" into a single value.
+ A list of fields which are cleaned into a single field. Each value in
+ ``clean`` 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 "compressed" into a single value.
``SplitDateTimeField``
~~~~~~~~~~~~~~~~~~~~~~
@@ -889,23 +890,23 @@ Takes one extra required argument:
* Error message keys: ``required``, ``invalid``, ``invalid_date``,
``invalid_time``
-Takes two optional arguments:
+ Takes two optional arguments:
-.. attribute:: SplitDateTimeField.input_date_formats
+ .. attribute:: input_date_formats
- A list of formats used to attempt to convert a string to a valid
- ``datetime.date`` object.
+ 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.
+ If no ``input_date_formats`` argument is provided, the default input formats
+ for ``DateField`` are used.
-.. attribute:: SplitDateTimeField.input_time_formats
+ .. attribute:: input_time_formats
- A list of formats used to attempt to convert a string to a valid
- ``datetime.time`` object.
+ 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.
+ If no ``input_time_formats`` argument is provided, the default input formats
+ for ``TimeField`` are used.
Fields which handle relationships
---------------------------------
@@ -930,45 +931,45 @@ objects (in the case of ``ModelMultipleChoiceField``) into the
* 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. A single argument is required:
+ Allows the selection of a single model object, suitable for
+ representing a foreign key. A single argument is required:
-.. attribute:: ModelChoiceField.queryset
+ .. attribute:: queryset
- A ``QuerySet`` of model objects from which the choices for the
- field will be derived, and which will be used to validate the
- user's selection.
+ A ``QuerySet`` of model objects from which the choices for the
+ field will be derived, and which will be used to validate the
+ user's selection.
-``ModelChoiceField`` also takes one optional argument:
+ ``ModelChoiceField`` also takes one optional argument:
-.. attribute:: ModelChoiceField.empty_label
+ .. attribute:: 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``::
+ 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)")
+ # A custom empty label
+ field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)")
- # No empty label
- field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
+ # 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``).
+ Note that if a ``ModelChoiceField`` is required and has a default
+ initial value, no empty choice is created (regardless of the value
+ of ``empty_label``).
-The ``__unicode__`` method of the model will be called to generate
-string representations of the objects for use in the field's choices;
-to provide customized representations, subclass ``ModelChoiceField``
-and override ``label_from_instance``. This method will receive a model
-object, and should return a string suitable for representing it. For
-example::
+ The ``__unicode__`` method of the model will be called to generate
+ string representations of the objects for use in the field's choices;
+ to provide customized representations, subclass ``ModelChoiceField``
+ and override ``label_from_instance``. This method will receive a model
+ object, and should return a string suitable for representing it. For
+ example::
- class MyModelChoiceField(ModelChoiceField):
- def label_from_instance(self, obj):
- return "My Object #%i" % obj.id
+ class MyModelChoiceField(ModelChoiceField):
+ def label_from_instance(self, obj):
+ return "My Object #%i" % obj.id
``ModelMultipleChoiceField``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -983,16 +984,16 @@ example::
* Error message keys: ``required``, ``list``, ``invalid_choice``,
``invalid_pk_value``
-Allows the selection of one or more model objects, suitable for
-representing a many-to-many relation. As with :class:`ModelChoiceField`,
-you can use ``label_from_instance`` to customize the object
-representations, and ``queryset`` is a required parameter:
+ Allows the selection of one or more model objects, suitable for
+ representing a many-to-many relation. As with :class:`ModelChoiceField`,
+ you can use ``label_from_instance`` to customize the object
+ representations, and ``queryset`` is a required parameter:
-.. attribute:: ModelMultipleChoiceField.queryset
+ .. attribute:: queryset
- A ``QuerySet`` of model objects from which the choices for the
- field will be derived, and which will be used to validate the
- user's selection.
+ A ``QuerySet`` of model objects from which the choices for the
+ field will be derived, and which will be used to validate the
+ user's selection.
Creating custom fields
----------------------
diff --git a/docs/ref/forms/validation.txt b/docs/ref/forms/validation.txt
index 5264279e8e..7657353495 100644
--- a/docs/ref/forms/validation.txt
+++ b/docs/ref/forms/validation.txt
@@ -28,72 +28,72 @@ after the field's ``to_python`` and ``validate`` methods have been called.
Validation of a Form is split into several steps, which can be customized or
overridden:
- * The ``to_python()`` method on a Field is the first step in every
- validation. It coerces the value to correct datatype and raises
- ``ValidationError`` if that is not possible. This method accepts the raw
- value from the widget and returns the converted value. For example, a
- FloatField will turn the data into a Python ``float`` or raise a
- ``ValidationError``.
+* The ``to_python()`` method on a Field is the first step in every
+ validation. It coerces the value to correct datatype and raises
+ ``ValidationError`` if that is not possible. This method accepts the raw
+ value from the widget and returns the converted value. For example, a
+ FloatField will turn the data into a Python ``float`` or raise a
+ ``ValidationError``.
- * The ``validate()`` method on a Field handles field-specific validation
- that is not suitable for a validator, It takes a value that has been
- coerced to correct datatype and raises ``ValidationError`` on any error.
- This method does not return anything and shouldn't alter the value. You
- should override it to handle validation logic that you can't or don't
- want to put in a validator.
+* The ``validate()`` method on a Field handles field-specific validation
+ that is not suitable for a validator, It takes a value that has been
+ coerced to correct datatype and raises ``ValidationError`` on any error.
+ This method does not return anything and shouldn't alter the value. You
+ should override it to handle validation logic that you can't or don't
+ want to put in a validator.
- * The ``run_validators()`` method on a Field runs all of the field's
- validators and aggregates all the errors into a single
- ``ValidationError``. You shouldn't need to override this method.
+* The ``run_validators()`` method on a Field runs all of the field's
+ validators and aggregates all the errors into a single
+ ``ValidationError``. You shouldn't need to override this method.
- * The ``clean()`` method on a Field subclass. This is responsible for
- running ``to_python``, ``validate`` and ``run_validators`` in the correct
- order and propagating their errors. If, at any time, any of the methods
- raise ``ValidationError``, the validation stops and that error is raised.
- This method returns the clean data, which is then inserted into the
- ``cleaned_data`` dictionary of the form.
+* The ``clean()`` method on a Field subclass. This is responsible for
+ running ``to_python``, ``validate`` and ``run_validators`` in the correct
+ order and propagating their errors. If, at any time, any of the methods
+ raise ``ValidationError``, the validation stops and that error is raised.
+ This method returns the clean data, which is then inserted into the
+ ``cleaned_data`` dictionary of the form.
- * The ``clean_<fieldname>()`` method in a form subclass -- where
- ``<fieldname>`` is replaced with the name of the form field attribute.
- This method does any cleaning that is specific to that particular
- attribute, unrelated to the type of field that it is. This method is not
- passed any parameters. You will need to look up the value of the field
- in ``self.cleaned_data`` and remember that it will be a Python object
- at this point, not the original string submitted in the form (it will be
- in ``cleaned_data`` because the general field ``clean()`` method, above,
- has already cleaned the data once).
+* The ``clean_<fieldname>()`` method in a form subclass -- where
+ ``<fieldname>`` is replaced with the name of the form field attribute.
+ This method does any cleaning that is specific to that particular
+ attribute, unrelated to the type of field that it is. This method is not
+ passed any parameters. You will need to look up the value of the field
+ in ``self.cleaned_data`` and remember that it will be a Python object
+ at this point, not the original string submitted in the form (it will be
+ in ``cleaned_data`` because the general field ``clean()`` method, above,
+ has already cleaned the data once).
- For example, if you wanted to validate that the contents of a
- ``CharField`` called ``serialnumber`` was unique,
- ``clean_serialnumber()`` would be the right place to do this. You don't
- need a specific field (it's just a ``CharField``), but you want a
- formfield-specific piece of validation and, possibly,
- cleaning/normalizing the data.
+ 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.
- Just like the general field ``clean()`` method, above, this method
- should return the cleaned data, regardless of whether it changed
- anything or not.
+ Just like the general field ``clean()`` method, above, this method
+ should return the cleaned data, regardless of whether it changed
+ anything or not.
- * The Form subclass's ``clean()`` method. This method can perform
- any validation that requires access to multiple fields from the form at
- once. This is where you might put in things to check that if field ``A``
- is supplied, field ``B`` must contain a valid email address and the
- like. The data that this method returns is the final ``cleaned_data``
- attribute for the form, so don't forget to return the full list of
- cleaned data if you override this method (by default, ``Form.clean()``
- just returns ``self.cleaned_data``).
+* The Form subclass's ``clean()`` method. This method can perform
+ any validation that requires access to multiple fields from the form at
+ once. This is where you might put in things to check that if field ``A``
+ is supplied, field ``B`` must contain a valid email address and the
+ like. The data that this method returns is the final ``cleaned_data``
+ attribute for the form, so don't forget to return the full list of
+ cleaned data if you override this method (by default, ``Form.clean()``
+ just returns ``self.cleaned_data``).
- Note that any errors raised by your ``Form.clean()`` override will not
- be associated with any field in particular. They go into a special
- "field" (called ``__all__``), which you can access via the
- ``non_field_errors()`` method if you need to. If you want to attach
- errors to a specific field in the form, you will need to access the
- ``_errors`` attribute on the form, which is `described later`_.
+ Note that any errors raised by your ``Form.clean()`` override will not
+ be associated with any field in particular. They go into a special
+ "field" (called ``__all__``), which you can access via the
+ ``non_field_errors()`` method if you need to. If you want to attach
+ errors to a specific field in the form, you will need to access the
+ ``_errors`` attribute on the form, which is `described later`_.
- Also note that there are special considerations when overriding
- the ``clean()`` method of a ``ModelForm`` subclass. (see the
- :ref:`ModelForm documentation
- <overriding-modelform-clean-method>` for more information)
+ Also note that there are special considerations when overriding
+ the ``clean()`` method of a ``ModelForm`` subclass. (see the
+ :ref:`ModelForm documentation
+ <overriding-modelform-clean-method>` 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
diff --git a/docs/ref/forms/widgets.txt b/docs/ref/forms/widgets.txt
index f0cde04c57..2b386c0864 100644
--- a/docs/ref/forms/widgets.txt
+++ b/docs/ref/forms/widgets.txt
@@ -21,16 +21,14 @@ which widget is used on which field, see the documentation about
However, if you want to use a different widget for a field, you can
just use the :attr:`~Field.widget` argument on the field definition. For
-example:
+example::
- .. code-block:: python
+ from django import forms
- from django import forms
-
- class CommentForm(forms.Form):
- name = forms.CharField()
- url = forms.URLField()
- comment = forms.CharField(widget=forms.Textarea)
+ 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 :class:`Textarea`
widget, rather than the default :class:`TextInput` widget.
@@ -42,25 +40,23 @@ 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
:attr:`~SelectDateWidget.years` attribute is set for a
-:class:`~django.forms.extras.widgets.SelectDateWidget`:
-
- .. code-block:: python
+:class:`~django.forms.extras.widgets.SelectDateWidget`::
- from django.forms.fields import DateField, ChoiceField, MultipleChoiceField
- from django.forms.widgets import RadioSelect, CheckboxSelectMultiple
- from django.forms.extras.widgets import SelectDateWidget
+ from django.forms.fields import DateField, ChoiceField, MultipleChoiceField
+ from django.forms.widgets import RadioSelect, CheckboxSelectMultiple
+ from django.forms.extras.widgets import SelectDateWidget
- BIRTH_YEAR_CHOICES = ('1980', '1981', '1982')
- GENDER_CHOICES = (('m', 'Male'), ('f', 'Female'))
- FAVORITE_COLORS_CHOICES = (('blue', 'Blue'),
- ('green', 'Green'),
- ('black', 'Black'))
+ BIRTH_YEAR_CHOICES = ('1980', '1981', '1982')
+ GENDER_CHOICES = (('m', 'Male'), ('f', 'Female'))
+ FAVORITE_COLORS_CHOICES = (('blue', 'Blue'),
+ ('green', 'Green'),
+ ('black', 'Black'))
- class SimpleForm(forms.Form):
- birth_year = DateField(widget=SelectDateWidget(years=BIRTH_YEAR_CHOICES))
- gender = ChoiceField(widget=RadioSelect, choices=GENDER_CHOICES)
- favorite_colors = forms.MultipleChoiceField(required=False,
- widget=CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES)
+ class SimpleForm(forms.Form):
+ birth_year = DateField(widget=SelectDateWidget(years=BIRTH_YEAR_CHOICES))
+ gender = ChoiceField(widget=RadioSelect, choices=GENDER_CHOICES)
+ favorite_colors = forms.MultipleChoiceField(required=False,
+ widget=CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES)
See the :ref:`built-in widgets` for more information about which widgets
are available and which arguments they accept.
@@ -78,21 +74,19 @@ buttons.
:class:`Select` widgets are used by default on :class:`ChoiceField` fields. The
choices displayed on the widget are inherited from the :class:`ChoiceField` and
changing :attr:`ChoiceField.choices` will update :attr:`Select.choices`. For
-example:
-
- .. code-block:: python
+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')]
+ >>> 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 :attr:`~Select.choices` attribute can however be used
@@ -113,55 +107,46 @@ specify additional attributes for each widget. When you specify a
widget, you can provide a list of attributes that will be added to the
rendered HTML for the widget.
-For example, take the following simple form:
+For example, take the following simple form::
- .. code-block:: python
+ from django import forms
- from django import forms
-
- class CommentForm(forms.Form):
- name = forms.CharField()
- url = forms.URLField()
- comment = forms.CharField()
+ class CommentForm(forms.Form):
+ name = forms.CharField()
+ url = forms.URLField()
+ comment = forms.CharField()
This form will include three default :class:`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:
-
- .. code-block:: python
-
- >>> f = CommentForm(auto_id=False)
- >>> f.as_table()
- <tr><th>Name:</th><td><input type="text" name="name" /></td></tr>
- <tr><th>Url:</th><td><input type="text" name="url"/></td></tr>
- <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
+provided for each widget will be rendered exactly the same::
+ >>> f = CommentForm(auto_id=False)
+ >>> f.as_table()
+ <tr><th>Name:</th><td><input type="text" name="name" /></td></tr>
+ <tr><th>Url:</th><td><input type="text" name="url"/></td></tr>
+ <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
On a real Web page, you probably don't want every widget to look the same. You
might want a larger input element for the comment, and you might want the
'name' widget to have some special CSS class. To do this, you use the
:attr:`Widget.attrs` argument when creating the widget:
-For example:
-
- .. code-block:: python
+For example::
- 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'}))
+ 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:
- .. code-block:: python
-
- >>> f = CommentForm(auto_id=False)
- >>> f.as_table()
- <tr><th>Name:</th><td><input type="text" name="name" class="special"/></td></tr>
- <tr><th>Url:</th><td><input type="text" name="url"/></td></tr>
- <tr><th>Comment:</th><td><input type="text" name="comment" size="40"/></td></tr>
+ >>> f = CommentForm(auto_id=False)
+ >>> f.as_table()
+ <tr><th>Name:</th><td><input type="text" name="name" class="special"/></td></tr>
+ <tr><th>Url:</th><td><input type="text" name="url"/></td></tr>
+ <tr><th>Comment:</th><td><input type="text" name="comment" size="40"/></td></tr>
.. _built-in widgets:
@@ -411,9 +396,7 @@ commonly used groups of widgets:
:class:`MultiWidget`'s subclasses must implement. This method takes a
single "compressed" value and returns a ``list``. An example of this is how
:class:`SplitDateTimeWidget` turns a :class:`datetime` value into a list
- with date and time split into two seperate values:
-
- .. code-block:: python
+ with date and time split into two seperate values::
class SplitDateTimeWidget(MultiWidget):