1. ===========
    
  2. Form fields
    
  3. ===========
    
  4. 
    
  5. .. module:: django.forms.fields
    
  6.    :synopsis: Django's built-in form fields.
    
  7. 
    
  8. .. currentmodule:: django.forms
    
  9. 
    
  10. .. class:: Field(**kwargs)
    
  11. 
    
  12. When you create a ``Form`` class, the most important part is defining the
    
  13. fields of the form. Each field has custom validation logic, along with a few
    
  14. other hooks.
    
  15. 
    
  16. .. method:: Field.clean(value)
    
  17. 
    
  18. Although the primary way you'll use ``Field`` classes is in ``Form`` classes,
    
  19. you can also instantiate them and use them directly to get a better idea of
    
  20. how they work. Each ``Field`` instance has a ``clean()`` method, which takes
    
  21. a single argument and either raises a
    
  22. ``django.core.exceptions.ValidationError`` exception or returns the clean
    
  23. value::
    
  24. 
    
  25.     >>> from django import forms
    
  26.     >>> f = forms.EmailField()
    
  27.     >>> f.clean('[email protected]')
    
  28.     '[email protected]'
    
  29.     >>> f.clean('invalid email address')
    
  30.     Traceback (most recent call last):
    
  31.     ...
    
  32.     ValidationError: ['Enter a valid email address.']
    
  33. 
    
  34. .. _core-field-arguments:
    
  35. 
    
  36. Core field arguments
    
  37. ====================
    
  38. 
    
  39. Each ``Field`` class constructor takes at least these arguments. Some
    
  40. ``Field`` classes take additional, field-specific arguments, but the following
    
  41. should *always* be accepted:
    
  42. 
    
  43. ``required``
    
  44. ------------
    
  45. 
    
  46. .. attribute:: Field.required
    
  47. 
    
  48. By default, each ``Field`` class assumes the value is required, so if you pass
    
  49. an empty value -- either ``None`` or the empty string (``""``) -- then
    
  50. ``clean()`` will raise a ``ValidationError`` exception::
    
  51. 
    
  52.     >>> from django import forms
    
  53.     >>> f = forms.CharField()
    
  54.     >>> f.clean('foo')
    
  55.     'foo'
    
  56.     >>> f.clean('')
    
  57.     Traceback (most recent call last):
    
  58.     ...
    
  59.     ValidationError: ['This field is required.']
    
  60.     >>> f.clean(None)
    
  61.     Traceback (most recent call last):
    
  62.     ...
    
  63.     ValidationError: ['This field is required.']
    
  64.     >>> f.clean(' ')
    
  65.     ' '
    
  66.     >>> f.clean(0)
    
  67.     '0'
    
  68.     >>> f.clean(True)
    
  69.     'True'
    
  70.     >>> f.clean(False)
    
  71.     'False'
    
  72. 
    
  73. To specify that a field is *not* required, pass ``required=False`` to the
    
  74. ``Field`` constructor::
    
  75. 
    
  76.     >>> f = forms.CharField(required=False)
    
  77.     >>> f.clean('foo')
    
  78.     'foo'
    
  79.     >>> f.clean('')
    
  80.     ''
    
  81.     >>> f.clean(None)
    
  82.     ''
    
  83.     >>> f.clean(0)
    
  84.     '0'
    
  85.     >>> f.clean(True)
    
  86.     'True'
    
  87.     >>> f.clean(False)
    
  88.     'False'
    
  89. 
    
  90. If a ``Field`` has ``required=False`` and you pass ``clean()`` an empty value,
    
  91. then ``clean()`` will return a *normalized* empty value rather than raising
    
  92. ``ValidationError``. For ``CharField``, this will return
    
  93. :attr:`~CharField.empty_value` which defaults to an empty string. For other
    
  94. ``Field`` classes, it might be ``None``. (This varies from field to field.)
    
  95. 
    
  96. Widgets of required form fields have the ``required`` HTML attribute. Set the
    
  97. :attr:`Form.use_required_attribute` attribute to ``False`` to disable it. The
    
  98. ``required`` attribute isn't included on forms of formsets because the browser
    
  99. validation may not be correct when adding and deleting formsets.
    
  100. 
    
  101. ``label``
    
  102. ---------
    
  103. 
    
  104. .. attribute:: Field.label
    
  105. 
    
  106. The ``label`` argument lets you specify the "human-friendly" label for this
    
  107. field. This is used when the ``Field`` is displayed in a ``Form``.
    
  108. 
    
  109. As explained in "Outputting forms as HTML" above, the default label for a
    
  110. ``Field`` is generated from the field name by converting all underscores to
    
  111. spaces and upper-casing the first letter. Specify ``label`` if that default
    
  112. behavior doesn't result in an adequate label.
    
  113. 
    
  114. Here's a full example ``Form`` that implements ``label`` for two of its fields.
    
  115. We've specified ``auto_id=False`` to simplify the output::
    
  116. 
    
  117.     >>> from django import forms
    
  118.     >>> class CommentForm(forms.Form):
    
  119.     ...     name = forms.CharField(label='Your name')
    
  120.     ...     url = forms.URLField(label='Your website', required=False)
    
  121.     ...     comment = forms.CharField()
    
  122.     >>> f = CommentForm(auto_id=False)
    
  123.     >>> print(f)
    
  124.     <tr><th>Your name:</th><td><input type="text" name="name" required></td></tr>
    
  125.     <tr><th>Your website:</th><td><input type="url" name="url"></td></tr>
    
  126.     <tr><th>Comment:</th><td><input type="text" name="comment" required></td></tr>
    
  127. 
    
  128. ``label_suffix``
    
  129. ----------------
    
  130. 
    
  131. .. attribute:: Field.label_suffix
    
  132. 
    
  133. The ``label_suffix`` argument lets you override the form's
    
  134. :attr:`~django.forms.Form.label_suffix` on a per-field basis::
    
  135. 
    
  136.     >>> class ContactForm(forms.Form):
    
  137.     ...     age = forms.IntegerField()
    
  138.     ...     nationality = forms.CharField()
    
  139.     ...     captcha_answer = forms.IntegerField(label='2 + 2', label_suffix=' =')
    
  140.     >>> f = ContactForm(label_suffix='?')
    
  141.     >>> print(f.as_p())
    
  142.     <p><label for="id_age">Age?</label> <input id="id_age" name="age" type="number" required></p>
    
  143.     <p><label for="id_nationality">Nationality?</label> <input id="id_nationality" name="nationality" type="text" required></p>
    
  144.     <p><label for="id_captcha_answer">2 + 2 =</label> <input id="id_captcha_answer" name="captcha_answer" type="number" required></p>
    
  145. 
    
  146. ``initial``
    
  147. -----------
    
  148. 
    
  149. .. attribute:: Field.initial
    
  150. 
    
  151. The ``initial`` argument lets you specify the initial value to use when
    
  152. rendering this ``Field`` in an unbound ``Form``.
    
  153. 
    
  154. To specify dynamic initial data, see the :attr:`Form.initial` parameter.
    
  155. 
    
  156. The use-case for this is when you want to display an "empty" form in which a
    
  157. field is initialized to a particular value. For example::
    
  158. 
    
  159.     >>> from django import forms
    
  160.     >>> class CommentForm(forms.Form):
    
  161.     ...     name = forms.CharField(initial='Your name')
    
  162.     ...     url = forms.URLField(initial='http://')
    
  163.     ...     comment = forms.CharField()
    
  164.     >>> f = CommentForm(auto_id=False)
    
  165.     >>> print(f)
    
  166.     <tr><th>Name:</th><td><input type="text" name="name" value="Your name" required></td></tr>
    
  167.     <tr><th>Url:</th><td><input type="url" name="url" value="http://" required></td></tr>
    
  168.     <tr><th>Comment:</th><td><input type="text" name="comment" required></td></tr>
    
  169. 
    
  170. You may be thinking, why not just pass a dictionary of the initial values as
    
  171. data when displaying the form? Well, if you do that, you'll trigger validation,
    
  172. and the HTML output will include any validation errors::
    
  173. 
    
  174.     >>> class CommentForm(forms.Form):
    
  175.     ...     name = forms.CharField()
    
  176.     ...     url = forms.URLField()
    
  177.     ...     comment = forms.CharField()
    
  178.     >>> default_data = {'name': 'Your name', 'url': 'http://'}
    
  179.     >>> f = CommentForm(default_data, auto_id=False)
    
  180.     >>> print(f)
    
  181.     <tr><th>Name:</th><td><input type="text" name="name" value="Your name" required></td></tr>
    
  182.     <tr><th>Url:</th><td><ul class="errorlist"><li>Enter a valid URL.</li></ul><input type="url" name="url" value="http://" required></td></tr>
    
  183.     <tr><th>Comment:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="comment" required></td></tr>
    
  184. 
    
  185. This is why ``initial`` values are only displayed for unbound forms. For bound
    
  186. forms, the HTML output will use the bound data.
    
  187. 
    
  188. Also note that ``initial`` values are *not* used as "fallback" data in
    
  189. validation if a particular field's value is not given. ``initial`` values are
    
  190. *only* intended for initial form display::
    
  191. 
    
  192.     >>> class CommentForm(forms.Form):
    
  193.     ...     name = forms.CharField(initial='Your name')
    
  194.     ...     url = forms.URLField(initial='http://')
    
  195.     ...     comment = forms.CharField()
    
  196.     >>> data = {'name': '', 'url': '', 'comment': 'Foo'}
    
  197.     >>> f = CommentForm(data)
    
  198.     >>> f.is_valid()
    
  199.     False
    
  200.     # The form does *not* fall back to using the initial values.
    
  201.     >>> f.errors
    
  202.     {'url': ['This field is required.'], 'name': ['This field is required.']}
    
  203. 
    
  204. Instead of a constant, you can also pass any callable::
    
  205. 
    
  206.     >>> import datetime
    
  207.     >>> class DateForm(forms.Form):
    
  208.     ...     day = forms.DateField(initial=datetime.date.today)
    
  209.     >>> print(DateForm())
    
  210.     <tr><th>Day:</th><td><input type="text" name="day" value="12/23/2008" required><td></tr>
    
  211. 
    
  212. The callable will be evaluated only when the unbound form is displayed, not when it is defined.
    
  213. 
    
  214. ``widget``
    
  215. ----------
    
  216. 
    
  217. .. attribute:: Field.widget
    
  218. 
    
  219. The ``widget`` argument lets you specify a ``Widget`` class to use when
    
  220. rendering this ``Field``. See :doc:`/ref/forms/widgets` for more information.
    
  221. 
    
  222. ``help_text``
    
  223. -------------
    
  224. 
    
  225. .. attribute:: Field.help_text
    
  226. 
    
  227. The ``help_text`` argument lets you specify descriptive text for this
    
  228. ``Field``. If you provide ``help_text``, it will be displayed next to the
    
  229. ``Field`` when the ``Field`` is rendered by one of the convenience ``Form``
    
  230. methods (e.g., ``as_ul()``).
    
  231. 
    
  232. Like the model field's :attr:`~django.db.models.Field.help_text`, this value
    
  233. isn't HTML-escaped in automatically-generated forms.
    
  234. 
    
  235. Here's a full example ``Form`` that implements ``help_text`` for two of its
    
  236. fields. We've specified ``auto_id=False`` to simplify the output::
    
  237. 
    
  238.     >>> from django import forms
    
  239.     >>> class HelpTextContactForm(forms.Form):
    
  240.     ...     subject = forms.CharField(max_length=100, help_text='100 characters max.')
    
  241.     ...     message = forms.CharField()
    
  242.     ...     sender = forms.EmailField(help_text='A valid email address, please.')
    
  243.     ...     cc_myself = forms.BooleanField(required=False)
    
  244.     >>> f = HelpTextContactForm(auto_id=False)
    
  245.     >>> print(f.as_table())
    
  246.     <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" required><br><span class="helptext">100 characters max.</span></td></tr>
    
  247.     <tr><th>Message:</th><td><input type="text" name="message" required></td></tr>
    
  248.     <tr><th>Sender:</th><td><input type="email" name="sender" required><br>A valid email address, please.</td></tr>
    
  249.     <tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself"></td></tr>
    
  250.     >>> print(f.as_ul()))
    
  251.     <li>Subject: <input type="text" name="subject" maxlength="100" required> <span class="helptext">100 characters max.</span></li>
    
  252.     <li>Message: <input type="text" name="message" required></li>
    
  253.     <li>Sender: <input type="email" name="sender" required> A valid email address, please.</li>
    
  254.     <li>Cc myself: <input type="checkbox" name="cc_myself"></li>
    
  255.     >>> print(f.as_p())
    
  256.     <p>Subject: <input type="text" name="subject" maxlength="100" required> <span class="helptext">100 characters max.</span></p>
    
  257.     <p>Message: <input type="text" name="message" required></p>
    
  258.     <p>Sender: <input type="email" name="sender" required> A valid email address, please.</p>
    
  259.     <p>Cc myself: <input type="checkbox" name="cc_myself"></p>
    
  260. 
    
  261. ``error_messages``
    
  262. ------------------
    
  263. 
    
  264. .. attribute:: Field.error_messages
    
  265. 
    
  266. The ``error_messages`` argument lets you override the default messages that the
    
  267. field will raise. Pass in a dictionary with keys matching the error messages you
    
  268. want to override. For example, here is the default error message::
    
  269. 
    
  270.     >>> from django import forms
    
  271.     >>> generic = forms.CharField()
    
  272.     >>> generic.clean('')
    
  273.     Traceback (most recent call last):
    
  274.       ...
    
  275.     ValidationError: ['This field is required.']
    
  276. 
    
  277. And here is a custom error message::
    
  278. 
    
  279.     >>> name = forms.CharField(error_messages={'required': 'Please enter your name'})
    
  280.     >>> name.clean('')
    
  281.     Traceback (most recent call last):
    
  282.       ...
    
  283.     ValidationError: ['Please enter your name']
    
  284. 
    
  285. In the `built-in Field classes`_ section below, each ``Field`` defines the
    
  286. error message keys it uses.
    
  287. 
    
  288. ``validators``
    
  289. --------------
    
  290. 
    
  291. .. attribute:: Field.validators
    
  292. 
    
  293. The ``validators`` argument lets you provide a list of validation functions
    
  294. for this field.
    
  295. 
    
  296. See the :doc:`validators documentation </ref/validators>` for more information.
    
  297. 
    
  298. ``localize``
    
  299. ------------
    
  300. 
    
  301. .. attribute:: Field.localize
    
  302. 
    
  303. The ``localize`` argument enables the localization of form data input, as well
    
  304. as the rendered output.
    
  305. 
    
  306. See the :doc:`format localization </topics/i18n/formatting>` documentation for
    
  307. more information.
    
  308. 
    
  309. ``disabled``
    
  310. ------------
    
  311. 
    
  312. .. attribute:: Field.disabled
    
  313. 
    
  314. The ``disabled`` boolean argument, when set to ``True``, disables a form field
    
  315. using the ``disabled`` HTML attribute so that it won't be editable by users.
    
  316. Even if a user tampers with the field's value submitted to the server, it will
    
  317. be ignored in favor of the value from the form's initial data.
    
  318. 
    
  319. Checking if the field data has changed
    
  320. ======================================
    
  321. 
    
  322. ``has_changed()``
    
  323. -----------------
    
  324. 
    
  325. .. method:: Field.has_changed()
    
  326. 
    
  327. The ``has_changed()`` method is used to determine if the field value has changed
    
  328. from the initial value. Returns ``True`` or ``False``.
    
  329. 
    
  330. See the :class:`Form.has_changed()` documentation for more information.
    
  331. 
    
  332. .. _built-in-fields:
    
  333. 
    
  334. Built-in ``Field`` classes
    
  335. ==========================
    
  336. 
    
  337. Naturally, the ``forms`` library comes with a set of ``Field`` classes that
    
  338. represent common validation needs. This section documents each built-in field.
    
  339. 
    
  340. For each field, we describe the default widget used if you don't specify
    
  341. ``widget``. We also specify the value returned when you provide an empty value
    
  342. (see the section on ``required`` above to understand what that means).
    
  343. 
    
  344. ``BooleanField``
    
  345. ----------------
    
  346. 
    
  347. .. class:: BooleanField(**kwargs)
    
  348. 
    
  349.     * Default widget: :class:`CheckboxInput`
    
  350.     * Empty value: ``False``
    
  351.     * Normalizes to: A Python ``True`` or ``False`` value.
    
  352.     * Validates that the value is ``True`` (e.g. the check box is checked) if
    
  353.       the field has ``required=True``.
    
  354.     * Error message keys: ``required``
    
  355. 
    
  356.     .. note::
    
  357. 
    
  358.         Since all ``Field`` subclasses have ``required=True`` by default, the
    
  359.         validation condition here is important. If you want to include a boolean
    
  360.         in your form that can be either ``True`` or ``False`` (e.g. a checked or
    
  361.         unchecked checkbox), you must remember to pass in ``required=False`` when
    
  362.         creating the ``BooleanField``.
    
  363. 
    
  364. ``CharField``
    
  365. -------------
    
  366. 
    
  367. .. class:: CharField(**kwargs)
    
  368. 
    
  369.     * Default widget: :class:`TextInput`
    
  370.     * Empty value: Whatever you've given as :attr:`empty_value`.
    
  371.     * Normalizes to: A string.
    
  372.     * Uses :class:`~django.core.validators.MaxLengthValidator` and
    
  373.       :class:`~django.core.validators.MinLengthValidator` if ``max_length`` and
    
  374.       ``min_length`` are provided. Otherwise, all inputs are valid.
    
  375.     * Error message keys: ``required``, ``max_length``, ``min_length``
    
  376. 
    
  377.     Has the following optional arguments for validation:
    
  378. 
    
  379.     .. attribute:: max_length
    
  380.     .. attribute:: min_length
    
  381. 
    
  382.         If provided, these arguments ensure that the string is at most or at
    
  383.         least the given length.
    
  384. 
    
  385.     .. attribute:: strip
    
  386. 
    
  387.        If ``True`` (default), the value will be stripped of leading and
    
  388.        trailing whitespace.
    
  389. 
    
  390.     .. attribute:: empty_value
    
  391. 
    
  392.        The value to use to represent "empty". Defaults to an empty string.
    
  393. 
    
  394. ``ChoiceField``
    
  395. ---------------
    
  396. 
    
  397. .. class:: ChoiceField(**kwargs)
    
  398. 
    
  399.     * Default widget: :class:`Select`
    
  400.     * Empty value: ``''`` (an empty string)
    
  401.     * Normalizes to: A string.
    
  402.     * Validates that the given value exists in the list of choices.
    
  403.     * Error message keys: ``required``, ``invalid_choice``
    
  404. 
    
  405.     The ``invalid_choice`` error message may contain ``%(value)s``, which will be
    
  406.     replaced with the selected choice.
    
  407. 
    
  408.     Takes one extra argument:
    
  409. 
    
  410.     .. attribute:: choices
    
  411. 
    
  412.         Either an :term:`iterable` of 2-tuples to use as choices for this
    
  413.         field, :ref:`enumeration <field-choices-enum-types>` choices, or a
    
  414.         callable that returns such an iterable. This argument accepts the same
    
  415.         formats as the ``choices`` argument to a model field. See the
    
  416.         :ref:`model field reference documentation on choices <field-choices>`
    
  417.         for more details. If the argument is a callable, it is evaluated each
    
  418.         time the field's form is initialized, in addition to during rendering.
    
  419.         Defaults to an empty list.
    
  420. 
    
  421. ``DateField``
    
  422. -------------
    
  423. 
    
  424. .. class:: DateField(**kwargs)
    
  425. 
    
  426.     * Default widget: :class:`DateInput`
    
  427.     * Empty value: ``None``
    
  428.     * Normalizes to: A Python ``datetime.date`` object.
    
  429.     * Validates that the given value is either a ``datetime.date``,
    
  430.       ``datetime.datetime`` or string formatted in a particular date format.
    
  431.     * Error message keys: ``required``, ``invalid``
    
  432. 
    
  433.     Takes one optional argument:
    
  434. 
    
  435.     .. attribute:: input_formats
    
  436. 
    
  437.         A list of formats used to attempt to convert a string to a valid
    
  438.         ``datetime.date`` object.
    
  439. 
    
  440.     If no ``input_formats`` argument is provided, the default input formats are
    
  441.     taken from :setting:`DATE_INPUT_FORMATS` if :setting:`USE_L10N` is
    
  442.     ``False``, or from the active locale format ``DATE_INPUT_FORMATS`` key if
    
  443.     localization is enabled. See also :doc:`format localization
    
  444.     </topics/i18n/formatting>`.
    
  445. 
    
  446. ``DateTimeField``
    
  447. -----------------
    
  448. 
    
  449. .. class:: DateTimeField(**kwargs)
    
  450. 
    
  451.     * Default widget: :class:`DateTimeInput`
    
  452.     * Empty value: ``None``
    
  453.     * Normalizes to: A Python ``datetime.datetime`` object.
    
  454.     * Validates that the given value is either a ``datetime.datetime``,
    
  455.       ``datetime.date`` or string formatted in a particular datetime format.
    
  456.     * Error message keys: ``required``, ``invalid``
    
  457. 
    
  458.     Takes one optional argument:
    
  459. 
    
  460.     .. attribute:: input_formats
    
  461. 
    
  462.         A list of formats used to attempt to convert a string to a valid
    
  463.         ``datetime.datetime`` object, in addition to ISO 8601 formats.
    
  464. 
    
  465.     The field always accepts strings in ISO 8601 formatted dates or similar
    
  466.     recognized by :func:`~django.utils.dateparse.parse_datetime`. Some examples
    
  467.     are::
    
  468. 
    
  469.         * '2006-10-25 14:30:59'
    
  470.         * '2006-10-25T14:30:59'
    
  471.         * '2006-10-25 14:30'
    
  472.         * '2006-10-25T14:30'
    
  473.         * '2006-10-25T14:30Z'
    
  474.         * '2006-10-25T14:30+02:00'
    
  475.         * '2006-10-25'
    
  476. 
    
  477.     If no ``input_formats`` argument is provided, the default input formats are
    
  478.     taken from :setting:`DATETIME_INPUT_FORMATS` and
    
  479.     :setting:`DATE_INPUT_FORMATS` if :setting:`USE_L10N` is ``False``, or from
    
  480.     the active locale format ``DATETIME_INPUT_FORMATS`` and
    
  481.     ``DATE_INPUT_FORMATS`` keys if localization is enabled. See also
    
  482.     :doc:`format localization </topics/i18n/formatting>`.
    
  483. 
    
  484. ``DecimalField``
    
  485. ----------------
    
  486. 
    
  487. .. class:: DecimalField(**kwargs)
    
  488. 
    
  489.     * Default widget: :class:`NumberInput` when :attr:`Field.localize` is
    
  490.       ``False``, else :class:`TextInput`.
    
  491.     * Empty value: ``None``
    
  492.     * Normalizes to: A Python ``decimal``.
    
  493.     * Validates that the given value is a decimal. Uses
    
  494.       :class:`~django.core.validators.MaxValueValidator` and
    
  495.       :class:`~django.core.validators.MinValueValidator` if ``max_value`` and
    
  496.       ``min_value`` are provided. Uses
    
  497.       :class:`~django.core.validators.StepValueValidator` if ``step_size`` is
    
  498.       provided. Leading and trailing whitespace is ignored.
    
  499.     * Error message keys: ``required``, ``invalid``, ``max_value``,
    
  500.       ``min_value``, ``max_digits``, ``max_decimal_places``,
    
  501.       ``max_whole_digits``, ``step_size``.
    
  502. 
    
  503.     The ``max_value`` and ``min_value`` error messages may contain
    
  504.     ``%(limit_value)s``, which will be substituted by the appropriate limit.
    
  505.     Similarly, the ``max_digits``, ``max_decimal_places`` and
    
  506.     ``max_whole_digits`` error messages may contain ``%(max)s``.
    
  507. 
    
  508.     Takes five optional arguments:
    
  509. 
    
  510.     .. attribute:: max_value
    
  511.     .. attribute:: min_value
    
  512. 
    
  513.         These control the range of values permitted in the field, and should be
    
  514.         given as ``decimal.Decimal`` values.
    
  515. 
    
  516.     .. attribute:: max_digits
    
  517. 
    
  518.         The maximum number of digits (those before the decimal point plus those
    
  519.         after the decimal point, with leading zeros stripped) permitted in the
    
  520.         value.
    
  521. 
    
  522.     .. attribute:: decimal_places
    
  523. 
    
  524.         The maximum number of decimal places permitted.
    
  525. 
    
  526.     .. attribute:: step_size
    
  527. 
    
  528.         Limit valid inputs to an integral multiple of ``step_size``.
    
  529. 
    
  530.     .. versionchanged:: 4.1
    
  531. 
    
  532.         The ``step_size`` argument was added.
    
  533. 
    
  534. ``DurationField``
    
  535. -----------------
    
  536. 
    
  537. .. class:: DurationField(**kwargs)
    
  538. 
    
  539.     * Default widget: :class:`TextInput`
    
  540.     * Empty value: ``None``
    
  541.     * Normalizes to: A Python :class:`~python:datetime.timedelta`.
    
  542.     * Validates that the given value is a string which can be converted into a
    
  543.       ``timedelta``. The value must be between :attr:`datetime.timedelta.min`
    
  544.       and :attr:`datetime.timedelta.max`.
    
  545.     * Error message keys: ``required``, ``invalid``, ``overflow``.
    
  546. 
    
  547.     Accepts any format understood by
    
  548.     :func:`~django.utils.dateparse.parse_duration`.
    
  549. 
    
  550. ``EmailField``
    
  551. --------------
    
  552. 
    
  553. .. class:: EmailField(**kwargs)
    
  554. 
    
  555.     * Default widget: :class:`EmailInput`
    
  556.     * Empty value: Whatever you've given as ``empty_value``.
    
  557.     * Normalizes to: A string.
    
  558.     * Uses :class:`~django.core.validators.EmailValidator` to validate that
    
  559.       the given value is a valid email address, using a moderately complex
    
  560.       regular expression.
    
  561.     * Error message keys: ``required``, ``invalid``
    
  562. 
    
  563.     Has the optional arguments ``max_length``, ``min_length``, and
    
  564.     ``empty_value`` which work just as they do for :class:`CharField`. The
    
  565.     ``max_length`` argument defaults to 320 (see :rfc:`3696#section-3`).
    
  566. 
    
  567.     .. versionchanged:: 3.2.20
    
  568. 
    
  569.         The default value for ``max_length`` was changed to 320 characters.
    
  570. 
    
  571. ``FileField``
    
  572. -------------
    
  573. 
    
  574. .. class:: FileField(**kwargs)
    
  575. 
    
  576.     * Default widget: :class:`ClearableFileInput`
    
  577.     * Empty value: ``None``
    
  578.     * Normalizes to: An ``UploadedFile`` object that wraps the file content
    
  579.       and file name into a single object.
    
  580.     * Can validate that non-empty file data has been bound to the form.
    
  581.     * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,
    
  582.       ``max_length``
    
  583. 
    
  584.     Has the optional arguments for validation: ``max_length`` and
    
  585.     ``allow_empty_file``. If provided, these ensure that the file name is at
    
  586.     most the given length, and that validation will succeed even if the file
    
  587.     content is empty.
    
  588. 
    
  589.     To learn more about the ``UploadedFile`` object, see the :doc:`file uploads
    
  590.     documentation </topics/http/file-uploads>`.
    
  591. 
    
  592.     When you use a ``FileField`` in a form, you must also remember to
    
  593.     :ref:`bind the file data to the form <binding-uploaded-files>`.
    
  594. 
    
  595.     The ``max_length`` error refers to the length of the filename. In the error
    
  596.     message for that key, ``%(max)d`` will be replaced with the maximum filename
    
  597.     length and ``%(length)d`` will be replaced with the current filename length.
    
  598. 
    
  599. ``FilePathField``
    
  600. -----------------
    
  601. 
    
  602. .. class:: FilePathField(**kwargs)
    
  603. 
    
  604.     * Default widget: :class:`Select`
    
  605.     * Empty value: ``''`` (an empty string)
    
  606.     * Normalizes to: A string.
    
  607.     * Validates that the selected choice exists in the list of choices.
    
  608.     * Error message keys: ``required``, ``invalid_choice``
    
  609. 
    
  610.     The field allows choosing from files inside a certain directory. It takes five
    
  611.     extra arguments; only ``path`` is required:
    
  612. 
    
  613.     .. attribute:: path
    
  614. 
    
  615.         The absolute path to the directory whose contents you want listed. This
    
  616.         directory must exist.
    
  617. 
    
  618.     .. attribute:: recursive
    
  619. 
    
  620.         If ``False`` (the default) only the direct contents of ``path`` will be
    
  621.         offered as choices. If ``True``, the directory will be descended into
    
  622.         recursively and all descendants will be listed as choices.
    
  623. 
    
  624.     .. attribute:: match
    
  625. 
    
  626.         A regular expression pattern; only files with names matching this expression
    
  627.         will be allowed as choices.
    
  628. 
    
  629.     .. attribute:: allow_files
    
  630. 
    
  631.         Optional.  Either ``True`` or ``False``.  Default is ``True``.  Specifies
    
  632.         whether files in the specified location should be included.  Either this or
    
  633.         :attr:`allow_folders` must be ``True``.
    
  634. 
    
  635.     .. attribute:: allow_folders
    
  636. 
    
  637.         Optional.  Either ``True`` or ``False``.  Default is ``False``.  Specifies
    
  638.         whether folders in the specified location should be included.  Either this or
    
  639.         :attr:`allow_files` must be ``True``.
    
  640. 
    
  641. 
    
  642. ``FloatField``
    
  643. --------------
    
  644. 
    
  645. .. class:: FloatField(**kwargs)
    
  646. 
    
  647.     * Default widget: :class:`NumberInput` when :attr:`Field.localize` is
    
  648.       ``False``, else :class:`TextInput`.
    
  649.     * Empty value: ``None``
    
  650.     * Normalizes to: A Python float.
    
  651.     * Validates that the given value is a float. Uses
    
  652.       :class:`~django.core.validators.MaxValueValidator` and
    
  653.       :class:`~django.core.validators.MinValueValidator` if ``max_value`` and
    
  654.       ``min_value`` are provided. Uses
    
  655.       :class:`~django.core.validators.StepValueValidator` if ``step_size`` is
    
  656.       provided. Leading and trailing whitespace is allowed, as in Python's
    
  657.       ``float()`` function.
    
  658.     * Error message keys: ``required``, ``invalid``, ``max_value``,
    
  659.       ``min_value``, ``step_size``.
    
  660. 
    
  661.     Takes three optional arguments:
    
  662. 
    
  663.     .. attribute:: max_value
    
  664.     .. attribute:: min_value
    
  665. 
    
  666.         These control the range of values permitted in the field.
    
  667. 
    
  668.     .. attribute:: step_size
    
  669. 
    
  670.         .. versionadded:: 4.1
    
  671. 
    
  672.         Limit valid inputs to an integral multiple of ``step_size``.
    
  673. 
    
  674. ``GenericIPAddressField``
    
  675. -------------------------
    
  676. 
    
  677. .. class:: GenericIPAddressField(**kwargs)
    
  678. 
    
  679.     A field containing either an IPv4 or an IPv6 address.
    
  680. 
    
  681.     * Default widget: :class:`TextInput`
    
  682.     * Empty value: ``''`` (an empty string)
    
  683.     * Normalizes to: A string. IPv6 addresses are normalized as described below.
    
  684.     * Validates that the given value is a valid IP address.
    
  685.     * Error message keys: ``required``, ``invalid``
    
  686. 
    
  687.     The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2,
    
  688.     including using the IPv4 format suggested in paragraph 3 of that section, like
    
  689.     ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to
    
  690.     ``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters
    
  691.     are converted to lowercase.
    
  692. 
    
  693.     Takes two optional arguments:
    
  694. 
    
  695.     .. attribute:: protocol
    
  696. 
    
  697.         Limits valid inputs to the specified protocol.
    
  698.         Accepted values are ``both`` (default), ``IPv4``
    
  699.         or ``IPv6``. Matching is case insensitive.
    
  700. 
    
  701.     .. attribute:: unpack_ipv4
    
  702. 
    
  703.         Unpacks IPv4 mapped addresses like ``::ffff:192.0.2.1``.
    
  704.         If this option is enabled that address would be unpacked to
    
  705.         ``192.0.2.1``. Default is disabled. Can only be used
    
  706.         when ``protocol`` is set to ``'both'``.
    
  707. 
    
  708. ``ImageField``
    
  709. --------------
    
  710. 
    
  711. .. class:: ImageField(**kwargs)
    
  712. 
    
  713.     * Default widget: :class:`ClearableFileInput`
    
  714.     * Empty value: ``None``
    
  715.     * Normalizes to: An ``UploadedFile`` object that wraps the file content
    
  716.       and file name into a single object.
    
  717.     * Validates that file data has been bound to the form. Also uses
    
  718.       :class:`~django.core.validators.FileExtensionValidator` to validate that
    
  719.       the file extension is supported by Pillow.
    
  720.     * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,
    
  721.       ``invalid_image``
    
  722. 
    
  723.     Using an ``ImageField`` requires that `Pillow`_ is installed with support
    
  724.     for the image formats you use. If you encounter a ``corrupt image`` error
    
  725.     when you upload an image, it usually means that Pillow doesn't understand
    
  726.     its format. To fix this, install the appropriate library and reinstall
    
  727.     Pillow.
    
  728. 
    
  729.     When you use an ``ImageField`` on a form, you must also remember to
    
  730.     :ref:`bind the file data to the form <binding-uploaded-files>`.
    
  731. 
    
  732.     After the field has been cleaned and validated, the ``UploadedFile``
    
  733.     object will have an additional ``image`` attribute containing the Pillow
    
  734.     `Image`_ instance used to check if the file was a valid image. Pillow
    
  735.     closes the underlying file descriptor after verifying an image, so while
    
  736.     non-image data attributes, such as ``format``, ``height``, and ``width``,
    
  737.     are available, methods that access the underlying image data, such as
    
  738.     ``getdata()`` or ``getpixel()``, cannot be used without reopening the file.
    
  739.     For example::
    
  740. 
    
  741.         >>> from PIL import Image
    
  742.         >>> from django import forms
    
  743.         >>> from django.core.files.uploadedfile import SimpleUploadedFile
    
  744.         >>> class ImageForm(forms.Form):
    
  745.         ...     img = forms.ImageField()
    
  746.         >>> file_data = {'img': SimpleUploadedFile('test.png', <file data>)}
    
  747.         >>> form = ImageForm({}, file_data)
    
  748.         # Pillow closes the underlying file descriptor.
    
  749.         >>> form.is_valid()
    
  750.         True
    
  751.         >>> image_field = form.cleaned_data['img']
    
  752.         >>> image_field.image
    
  753.         <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=191x287 at 0x7F5985045C18>
    
  754.         >>> image_field.image.width
    
  755.         191
    
  756.         >>> image_field.image.height
    
  757.         287
    
  758.         >>> image_field.image.format
    
  759.         'PNG'
    
  760.         >>> image_field.image.getdata()
    
  761.         # Raises AttributeError: 'NoneType' object has no attribute 'seek'.
    
  762.         >>> image = Image.open(image_field)
    
  763.         >>> image.getdata()
    
  764.         <ImagingCore object at 0x7f5984f874b0>
    
  765. 
    
  766.     Additionally, ``UploadedFile.content_type`` will be updated with the
    
  767.     image's content type if Pillow can determine it, otherwise it will be set
    
  768.     to ``None``.
    
  769. 
    
  770. .. _Pillow: https://pillow.readthedocs.io/en/latest/
    
  771. .. _Image: https://pillow.readthedocs.io/en/latest/reference/Image.html
    
  772. 
    
  773. ``IntegerField``
    
  774. ----------------
    
  775. 
    
  776. .. class:: IntegerField(**kwargs)
    
  777. 
    
  778.     * Default widget: :class:`NumberInput` when :attr:`Field.localize` is
    
  779.       ``False``, else :class:`TextInput`.
    
  780.     * Empty value: ``None``
    
  781.     * Normalizes to: A Python integer.
    
  782.     * Validates that the given value is an integer. Uses
    
  783.       :class:`~django.core.validators.MaxValueValidator` and
    
  784.       :class:`~django.core.validators.MinValueValidator` if ``max_value`` and
    
  785.       ``min_value`` are provided. Uses
    
  786.       :class:`~django.core.validators.StepValueValidator` if ``step_size`` is
    
  787.       provided. Leading and trailing whitespace is allowed, as in Python's
    
  788.       ``int()`` function.
    
  789.     * Error message keys: ``required``, ``invalid``, ``max_value``,
    
  790.       ``min_value``, ``step_size``
    
  791. 
    
  792.     The ``max_value``, ``min_value`` and ``step_size`` error messages may
    
  793.     contain ``%(limit_value)s``, which will be substituted by the appropriate
    
  794.     limit.
    
  795. 
    
  796.     Takes three optional arguments for validation:
    
  797. 
    
  798.     .. attribute:: max_value
    
  799.     .. attribute:: min_value
    
  800. 
    
  801.         These control the range of values permitted in the field.
    
  802. 
    
  803.     .. attribute:: step_size
    
  804. 
    
  805.         .. versionadded:: 4.1
    
  806. 
    
  807.         Limit valid inputs to an integral multiple of ``step_size``.
    
  808. 
    
  809. ``JSONField``
    
  810. -------------
    
  811. 
    
  812. .. class:: JSONField(encoder=None, decoder=None, **kwargs)
    
  813. 
    
  814.     A field which accepts JSON encoded data for a
    
  815.     :class:`~django.db.models.JSONField`.
    
  816. 
    
  817.     * Default widget: :class:`Textarea`
    
  818.     * Empty value: ``None``
    
  819.     * Normalizes to: A Python representation of the JSON value (usually as a
    
  820.       ``dict``, ``list``, or ``None``), depending on :attr:`JSONField.decoder`.
    
  821.     * Validates that the given value is a valid JSON.
    
  822.     * Error message keys: ``required``, ``invalid``
    
  823. 
    
  824.     Takes two optional arguments:
    
  825. 
    
  826.     .. attribute:: encoder
    
  827. 
    
  828.         A :py:class:`json.JSONEncoder` subclass to serialize data types not
    
  829.         supported by the standard JSON serializer (e.g. ``datetime.datetime``
    
  830.         or :class:`~python:uuid.UUID`). For example, you can use the
    
  831.         :class:`~django.core.serializers.json.DjangoJSONEncoder` class.
    
  832. 
    
  833.         Defaults to ``json.JSONEncoder``.
    
  834. 
    
  835.     .. attribute:: decoder
    
  836. 
    
  837.         A :py:class:`json.JSONDecoder` subclass to deserialize the input. Your
    
  838.         deserialization may need to account for the fact that you can't be
    
  839.         certain of the input type. For example, you run the risk of returning a
    
  840.         ``datetime`` that was actually a string that just happened to be in the
    
  841.         same format chosen for ``datetime``\s.
    
  842. 
    
  843.         The ``decoder`` can be used to validate the input. If
    
  844.         :py:class:`json.JSONDecodeError` is raised during the deserialization,
    
  845.         a ``ValidationError`` will be raised.
    
  846. 
    
  847.         Defaults to ``json.JSONDecoder``.
    
  848. 
    
  849.     .. note::
    
  850. 
    
  851.         If you use a :class:`ModelForm <django.forms.ModelForm>`, the
    
  852.         ``encoder`` and ``decoder`` from :class:`~django.db.models.JSONField`
    
  853.         will be used.
    
  854. 
    
  855.     .. admonition:: User friendly forms
    
  856. 
    
  857.         ``JSONField`` is not particularly user friendly in most cases. However,
    
  858.         it is a useful way to format data from a client-side widget for
    
  859.         submission to the server.
    
  860. 
    
  861. ``MultipleChoiceField``
    
  862. -----------------------
    
  863. 
    
  864. .. class:: MultipleChoiceField(**kwargs)
    
  865. 
    
  866.     * Default widget: :class:`SelectMultiple`
    
  867.     * Empty value: ``[]`` (an empty list)
    
  868.     * Normalizes to: A list of strings.
    
  869.     * Validates that every value in the given list of values exists in the list
    
  870.       of choices.
    
  871.     * Error message keys: ``required``, ``invalid_choice``, ``invalid_list``
    
  872. 
    
  873.     The ``invalid_choice`` error message may contain ``%(value)s``, which will be
    
  874.     replaced with the selected choice.
    
  875. 
    
  876.     Takes one extra required argument, ``choices``, as for :class:`ChoiceField`.
    
  877. 
    
  878. ``NullBooleanField``
    
  879. --------------------
    
  880. 
    
  881. .. class:: NullBooleanField(**kwargs)
    
  882. 
    
  883.     * Default widget: :class:`NullBooleanSelect`
    
  884.     * Empty value: ``None``
    
  885.     * Normalizes to: A Python ``True``, ``False`` or ``None`` value.
    
  886.     * Validates nothing (i.e., it never raises a ``ValidationError``).
    
  887. 
    
  888.     ``NullBooleanField`` may be used with widgets such as
    
  889.     :class:`~django.forms.Select` or :class:`~django.forms.RadioSelect`
    
  890.     by providing the widget ``choices``::
    
  891. 
    
  892.         NullBooleanField(
    
  893.             widget=Select(
    
  894.                 choices=[
    
  895.                     ('', 'Unknown'),
    
  896.                     (True, 'Yes'),
    
  897.                     (False, 'No'),
    
  898.                 ]
    
  899.             )
    
  900.         )
    
  901. 
    
  902. ``RegexField``
    
  903. --------------
    
  904. 
    
  905. .. class:: RegexField(**kwargs)
    
  906. 
    
  907.     * Default widget: :class:`TextInput`
    
  908.     * Empty value: Whatever you've given as ``empty_value``.
    
  909.     * Normalizes to: A string.
    
  910.     * Uses :class:`~django.core.validators.RegexValidator` to validate that
    
  911.       the given value matches a certain regular expression.
    
  912.     * Error message keys: ``required``, ``invalid``
    
  913. 
    
  914.     Takes one required argument:
    
  915. 
    
  916.     .. attribute:: regex
    
  917. 
    
  918.         A regular expression specified either as a string or a compiled regular
    
  919.         expression object.
    
  920. 
    
  921.     Also takes ``max_length``, ``min_length``, ``strip``, and ``empty_value``
    
  922.     which work just as they do for :class:`CharField`.
    
  923. 
    
  924.     .. attribute:: strip
    
  925. 
    
  926.         Defaults to ``False``. If enabled, stripping will be applied before the
    
  927.         regex validation.
    
  928. 
    
  929. ``SlugField``
    
  930. -------------
    
  931. 
    
  932. .. class:: SlugField(**kwargs)
    
  933. 
    
  934.    * Default widget: :class:`TextInput`
    
  935.    * Empty value: Whatever you've given as :attr:`empty_value`.
    
  936.    * Normalizes to: A string.
    
  937.    * Uses :class:`~django.core.validators.validate_slug` or
    
  938.      :class:`~django.core.validators.validate_unicode_slug` to validate that
    
  939.      the given value contains only letters, numbers, underscores, and hyphens.
    
  940.    * Error messages: ``required``, ``invalid``
    
  941. 
    
  942.    This field is intended for use in representing a model
    
  943.    :class:`~django.db.models.SlugField` in forms.
    
  944. 
    
  945.    Takes two optional parameters:
    
  946. 
    
  947.    .. attribute:: allow_unicode
    
  948. 
    
  949.        A boolean instructing the field to accept Unicode letters in addition
    
  950.        to ASCII letters. Defaults to ``False``.
    
  951. 
    
  952.    .. attribute:: empty_value
    
  953. 
    
  954.        The value to use to represent "empty". Defaults to an empty string.
    
  955. 
    
  956. ``TimeField``
    
  957. -------------
    
  958. 
    
  959. .. class:: TimeField(**kwargs)
    
  960. 
    
  961.     * Default widget: :class:`TimeInput`
    
  962.     * Empty value: ``None``
    
  963.     * Normalizes to: A Python ``datetime.time`` object.
    
  964.     * Validates that the given value is either a ``datetime.time`` or string
    
  965.       formatted in a particular time format.
    
  966.     * Error message keys: ``required``, ``invalid``
    
  967. 
    
  968.     Takes one optional argument:
    
  969. 
    
  970.     .. attribute:: input_formats
    
  971. 
    
  972.         A list of formats used to attempt to convert a string to a valid
    
  973.         ``datetime.time`` object.
    
  974. 
    
  975.     If no ``input_formats`` argument is provided, the default input formats are
    
  976.     taken from :setting:`TIME_INPUT_FORMATS` if :setting:`USE_L10N` is
    
  977.     ``False``, or from the active locale format ``TIME_INPUT_FORMATS`` key if
    
  978.     localization is enabled. See also :doc:`format localization
    
  979.     </topics/i18n/formatting>`.
    
  980. 
    
  981. ``TypedChoiceField``
    
  982. --------------------
    
  983. 
    
  984. .. class:: TypedChoiceField(**kwargs)
    
  985. 
    
  986.     Just like a :class:`ChoiceField`, except :class:`TypedChoiceField` takes two
    
  987.     extra arguments, :attr:`coerce` and :attr:`empty_value`.
    
  988. 
    
  989.     * Default widget: :class:`Select`
    
  990.     * Empty value: Whatever you've given as :attr:`empty_value`.
    
  991.     * Normalizes to: A value of the type provided by the :attr:`coerce`
    
  992.       argument.
    
  993.     * Validates that the given value exists in the list of choices and can be
    
  994.       coerced.
    
  995.     * Error message keys: ``required``, ``invalid_choice``
    
  996. 
    
  997.     Takes extra arguments:
    
  998. 
    
  999.     .. attribute:: coerce
    
  1000. 
    
  1001.         A function that takes one argument and returns a coerced value. Examples
    
  1002.         include the built-in ``int``, ``float``, ``bool`` and other types. Defaults
    
  1003.         to an identity function. Note that coercion happens after input
    
  1004.         validation, so it is possible to coerce to a value not present in
    
  1005.         ``choices``.
    
  1006. 
    
  1007.     .. attribute:: empty_value
    
  1008. 
    
  1009.         The value to use to represent "empty." Defaults to the empty string;
    
  1010.         ``None`` is another common choice here. Note that this value will not be
    
  1011.         coerced by the function given in the ``coerce`` argument, so choose it
    
  1012.         accordingly.
    
  1013. 
    
  1014. ``TypedMultipleChoiceField``
    
  1015. ----------------------------
    
  1016. 
    
  1017. .. class:: TypedMultipleChoiceField(**kwargs)
    
  1018. 
    
  1019.     Just like a :class:`MultipleChoiceField`, except :class:`TypedMultipleChoiceField`
    
  1020.     takes two extra arguments, ``coerce`` and ``empty_value``.
    
  1021. 
    
  1022.     * Default widget: :class:`SelectMultiple`
    
  1023.     * Empty value: Whatever you've given as ``empty_value``
    
  1024.     * Normalizes to: A list of values of the type provided by the ``coerce``
    
  1025.       argument.
    
  1026.     * Validates that the given values exists in the list of choices and can be
    
  1027.       coerced.
    
  1028.     * Error message keys: ``required``, ``invalid_choice``
    
  1029. 
    
  1030.     The ``invalid_choice`` error message may contain ``%(value)s``, which will be
    
  1031.     replaced with the selected choice.
    
  1032. 
    
  1033.     Takes two extra arguments, ``coerce`` and ``empty_value``, as for
    
  1034.     :class:`TypedChoiceField`.
    
  1035. 
    
  1036. ``URLField``
    
  1037. ------------
    
  1038. 
    
  1039. .. class:: URLField(**kwargs)
    
  1040. 
    
  1041.     * Default widget: :class:`URLInput`
    
  1042.     * Empty value: Whatever you've given as ``empty_value``.
    
  1043.     * Normalizes to: A string.
    
  1044.     * Uses :class:`~django.core.validators.URLValidator` to validate that the
    
  1045.       given value is a valid URL.
    
  1046.     * Error message keys: ``required``, ``invalid``
    
  1047. 
    
  1048.     Has the optional arguments ``max_length``, ``min_length``, and
    
  1049.     ``empty_value`` which work just as they do for :class:`CharField`.
    
  1050. 
    
  1051. ``UUIDField``
    
  1052. -------------
    
  1053. 
    
  1054. .. class:: UUIDField(**kwargs)
    
  1055. 
    
  1056.     * Default widget: :class:`TextInput`
    
  1057.     * Empty value: ``None``
    
  1058.     * Normalizes to: A :class:`~python:uuid.UUID` object.
    
  1059.     * Error message keys: ``required``, ``invalid``
    
  1060. 
    
  1061.     This field will accept any string format accepted as the ``hex`` argument
    
  1062.     to the :class:`~python:uuid.UUID` constructor.
    
  1063. 
    
  1064. Slightly complex built-in ``Field`` classes
    
  1065. ===========================================
    
  1066. 
    
  1067. ``ComboField``
    
  1068. --------------
    
  1069. 
    
  1070. .. class:: ComboField(**kwargs)
    
  1071. 
    
  1072.     * Default widget: :class:`TextInput`
    
  1073.     * Empty value: ``''`` (an empty string)
    
  1074.     * Normalizes to: A string.
    
  1075.     * Validates the given value against each of the fields specified
    
  1076.       as an argument to the ``ComboField``.
    
  1077.     * Error message keys: ``required``, ``invalid``
    
  1078. 
    
  1079.     Takes one extra required argument:
    
  1080. 
    
  1081.     .. attribute:: fields
    
  1082. 
    
  1083.         The list of fields that should be used to validate the field's value (in
    
  1084.         the order in which they are provided).
    
  1085. 
    
  1086.             >>> from django.forms import ComboField
    
  1087.             >>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
    
  1088.             >>> f.clean('[email protected]')
    
  1089.             '[email protected]'
    
  1090.             >>> f.clean('[email protected]')
    
  1091.             Traceback (most recent call last):
    
  1092.             ...
    
  1093.             ValidationError: ['Ensure this value has at most 20 characters (it has 28).']
    
  1094. 
    
  1095. ``MultiValueField``
    
  1096. -------------------
    
  1097. 
    
  1098. .. class:: MultiValueField(fields=(), **kwargs)
    
  1099. 
    
  1100.     * Default widget: :class:`TextInput`
    
  1101.     * Empty value: ``''`` (an empty string)
    
  1102.     * Normalizes to: the type returned by the ``compress`` method of the subclass.
    
  1103.     * Validates the given value against each of the fields specified
    
  1104.       as an argument to the ``MultiValueField``.
    
  1105.     * Error message keys: ``required``, ``invalid``, ``incomplete``
    
  1106. 
    
  1107.     Aggregates the logic of multiple fields that together produce a single
    
  1108.     value.
    
  1109. 
    
  1110.     This field is abstract and must be subclassed. In contrast with the
    
  1111.     single-value fields, subclasses of :class:`MultiValueField` must not
    
  1112.     implement :meth:`~django.forms.Field.clean` but instead - implement
    
  1113.     :meth:`~MultiValueField.compress`.
    
  1114. 
    
  1115.     Takes one extra required argument:
    
  1116. 
    
  1117.     .. attribute:: fields
    
  1118. 
    
  1119.         A tuple of fields whose values are cleaned and subsequently combined
    
  1120.         into a single value.  Each value of the field is cleaned by the
    
  1121.         corresponding field in ``fields`` -- the first value is cleaned by the
    
  1122.         first field, the second value is cleaned by the second field, etc.
    
  1123.         Once all fields are cleaned, the list of clean values is combined into
    
  1124.         a single value by :meth:`~MultiValueField.compress`.
    
  1125. 
    
  1126.     Also takes some optional arguments:
    
  1127. 
    
  1128.     .. attribute:: require_all_fields
    
  1129. 
    
  1130.         Defaults to ``True``, in which case a ``required`` validation error
    
  1131.         will be raised if no value is supplied for any field.
    
  1132. 
    
  1133.         When set to ``False``, the :attr:`Field.required` attribute can be set
    
  1134.         to ``False`` for individual fields to make them optional. If no value
    
  1135.         is supplied for a required field, an ``incomplete`` validation error
    
  1136.         will be raised.
    
  1137. 
    
  1138.         A default ``incomplete`` error message can be defined on the
    
  1139.         :class:`MultiValueField` subclass, or different messages can be defined
    
  1140.         on each individual field. For example::
    
  1141. 
    
  1142.             from django.core.validators import RegexValidator
    
  1143. 
    
  1144.             class PhoneField(MultiValueField):
    
  1145.                 def __init__(self, **kwargs):
    
  1146.                     # Define one message for all fields.
    
  1147.                     error_messages = {
    
  1148.                         'incomplete': 'Enter a country calling code and a phone number.',
    
  1149.                     }
    
  1150.                     # Or define a different message for each field.
    
  1151.                     fields = (
    
  1152.                         CharField(
    
  1153.                             error_messages={'incomplete': 'Enter a country calling code.'},
    
  1154.                             validators=[
    
  1155.                                 RegexValidator(r'^[0-9]+$', 'Enter a valid country calling code.'),
    
  1156.                             ],
    
  1157.                         ),
    
  1158.                         CharField(
    
  1159.                             error_messages={'incomplete': 'Enter a phone number.'},
    
  1160.                             validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid phone number.')],
    
  1161.                         ),
    
  1162.                         CharField(
    
  1163.                             validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid extension.')],
    
  1164.                             required=False,
    
  1165.                         ),
    
  1166.                     )
    
  1167.                     super().__init__(
    
  1168.                         error_messages=error_messages, fields=fields,
    
  1169.                         require_all_fields=False, **kwargs
    
  1170.                     )
    
  1171. 
    
  1172.     .. attribute:: MultiValueField.widget
    
  1173. 
    
  1174.         Must be a subclass of :class:`django.forms.MultiWidget`.
    
  1175.         Default value is :class:`~django.forms.TextInput`, which
    
  1176.         probably is not very useful in this case.
    
  1177. 
    
  1178.     .. method:: compress(data_list)
    
  1179. 
    
  1180.         Takes a list of valid values and returns  a "compressed" version of
    
  1181.         those values -- in a single value. For example,
    
  1182.         :class:`SplitDateTimeField` is a subclass which combines a time field
    
  1183.         and a date field into a ``datetime`` object.
    
  1184. 
    
  1185.         This method must be implemented in the subclasses.
    
  1186. 
    
  1187. ``SplitDateTimeField``
    
  1188. ----------------------
    
  1189. 
    
  1190. .. class:: SplitDateTimeField(**kwargs)
    
  1191. 
    
  1192.     * Default widget: :class:`SplitDateTimeWidget`
    
  1193.     * Empty value: ``None``
    
  1194.     * Normalizes to: A Python ``datetime.datetime`` object.
    
  1195.     * Validates that the given value is a ``datetime.datetime`` or string
    
  1196.       formatted in a particular datetime format.
    
  1197.     * Error message keys: ``required``, ``invalid``, ``invalid_date``,
    
  1198.       ``invalid_time``
    
  1199. 
    
  1200.     Takes two optional arguments:
    
  1201. 
    
  1202.     .. attribute:: input_date_formats
    
  1203. 
    
  1204.         A list of formats used to attempt to convert a string to a valid
    
  1205.         ``datetime.date`` object.
    
  1206. 
    
  1207.     If no ``input_date_formats`` argument is provided, the default input formats
    
  1208.     for :class:`DateField` are used.
    
  1209. 
    
  1210.     .. attribute:: input_time_formats
    
  1211. 
    
  1212.         A list of formats used to attempt to convert a string to a valid
    
  1213.         ``datetime.time`` object.
    
  1214. 
    
  1215.     If no ``input_time_formats`` argument is provided, the default input formats
    
  1216.     for :class:`TimeField` are used.
    
  1217. 
    
  1218. .. _fields-which-handle-relationships:
    
  1219. 
    
  1220. Fields which handle relationships
    
  1221. =================================
    
  1222. 
    
  1223. Two fields are available for representing relationships between
    
  1224. models: :class:`ModelChoiceField` and
    
  1225. :class:`ModelMultipleChoiceField`.  Both of these fields require a
    
  1226. single ``queryset`` parameter that is used to create the choices for
    
  1227. the field.  Upon form validation, these fields will place either one
    
  1228. model object (in the case of ``ModelChoiceField``) or multiple model
    
  1229. objects (in the case of ``ModelMultipleChoiceField``) into the
    
  1230. ``cleaned_data`` dictionary of the form.
    
  1231. 
    
  1232. For more complex uses, you can specify ``queryset=None`` when declaring the
    
  1233. form field and then populate the ``queryset`` in the form's ``__init__()``
    
  1234. method::
    
  1235. 
    
  1236.     class FooMultipleChoiceForm(forms.Form):
    
  1237.         foo_select = forms.ModelMultipleChoiceField(queryset=None)
    
  1238. 
    
  1239.         def __init__(self, *args, **kwargs):
    
  1240.             super().__init__(*args, **kwargs)
    
  1241.             self.fields['foo_select'].queryset = ...
    
  1242. 
    
  1243. Both ``ModelChoiceField`` and ``ModelMultipleChoiceField`` have an ``iterator``
    
  1244. attribute which specifies the class used to iterate over the queryset when
    
  1245. generating choices. See :ref:`iterating-relationship-choices` for details.
    
  1246. 
    
  1247. ``ModelChoiceField``
    
  1248. --------------------
    
  1249. 
    
  1250. .. class:: ModelChoiceField(**kwargs)
    
  1251. 
    
  1252.     * Default widget: :class:`Select`
    
  1253.     * Empty value: ``None``
    
  1254.     * Normalizes to: A model instance.
    
  1255.     * Validates that the given id exists in the queryset.
    
  1256.     * Error message keys: ``required``, ``invalid_choice``
    
  1257. 
    
  1258.     The ``invalid_choice`` error message may contain ``%(value)s``, which will
    
  1259.     be replaced with the selected choice.
    
  1260. 
    
  1261.     Allows the selection of a single model object, suitable for representing a
    
  1262.     foreign key. Note that the default widget for ``ModelChoiceField`` becomes
    
  1263.     impractical when the number of entries increases. You should avoid using it
    
  1264.     for more than 100 items.
    
  1265. 
    
  1266.     A single argument is required:
    
  1267. 
    
  1268.     .. attribute:: queryset
    
  1269. 
    
  1270.         A ``QuerySet`` of model objects from which the choices for the field
    
  1271.         are derived and which is used to validate the user's selection. It's
    
  1272.         evaluated when the form is rendered.
    
  1273. 
    
  1274.     ``ModelChoiceField`` also takes several optional arguments:
    
  1275. 
    
  1276.     .. attribute:: empty_label
    
  1277. 
    
  1278.         By default the ``<select>`` widget used by ``ModelChoiceField`` will have an
    
  1279.         empty choice at the top of the list. You can change the text of this
    
  1280.         label (which is ``"---------"`` by default) with the ``empty_label``
    
  1281.         attribute, or you can disable the empty label entirely by setting
    
  1282.         ``empty_label`` to ``None``::
    
  1283. 
    
  1284.             # A custom empty label
    
  1285.             field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)")
    
  1286. 
    
  1287.             # No empty label
    
  1288.             field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
    
  1289. 
    
  1290.         Note that no empty choice is created (regardless of the value of
    
  1291.         ``empty_label``) if a ``ModelChoiceField`` is required and has a
    
  1292.         default initial value, or a ``widget`` is set to
    
  1293.         :class:`~django.forms.RadioSelect` and the
    
  1294.         :attr:`~ModelChoiceField.blank` argument is ``False``.
    
  1295. 
    
  1296.     .. attribute:: to_field_name
    
  1297. 
    
  1298.         This optional argument is used to specify the field to use as the value
    
  1299.         of the choices in the field's widget. Be sure it's a unique field for
    
  1300.         the model, otherwise the selected value could match more than one
    
  1301.         object. By default it is set to ``None``, in which case the primary key
    
  1302.         of each object will be used. For example::
    
  1303. 
    
  1304.             # No custom to_field_name
    
  1305.             field1 = forms.ModelChoiceField(queryset=...)
    
  1306. 
    
  1307.         would yield:
    
  1308. 
    
  1309.         .. code-block:: html
    
  1310. 
    
  1311.             <select id="id_field1" name="field1">
    
  1312.             <option value="obj1.pk">Object1</option>
    
  1313.             <option value="obj2.pk">Object2</option>
    
  1314.             ...
    
  1315.             </select>
    
  1316. 
    
  1317.         and::
    
  1318. 
    
  1319.             # to_field_name provided
    
  1320.             field2 = forms.ModelChoiceField(queryset=..., to_field_name="name")
    
  1321. 
    
  1322.         would yield:
    
  1323. 
    
  1324.         .. code-block:: html
    
  1325. 
    
  1326.             <select id="id_field2" name="field2">
    
  1327.             <option value="obj1.name">Object1</option>
    
  1328.             <option value="obj2.name">Object2</option>
    
  1329.             ...
    
  1330.             </select>
    
  1331. 
    
  1332.     .. attribute:: blank
    
  1333. 
    
  1334.         When using the :class:`~django.forms.RadioSelect` widget, this optional
    
  1335.         boolean argument determines whether an empty choice is created. By
    
  1336.         default, ``blank`` is ``False``, in which case no empty choice is
    
  1337.         created.
    
  1338. 
    
  1339.     ``ModelChoiceField`` also has the attribute:
    
  1340. 
    
  1341.     .. attribute:: iterator
    
  1342. 
    
  1343.         The iterator class used to generate field choices from ``queryset``. By
    
  1344.         default, :class:`ModelChoiceIterator`.
    
  1345. 
    
  1346.     The ``__str__()`` method of the model will be called to generate string
    
  1347.     representations of the objects for use in the field's choices. To provide
    
  1348.     customized representations, subclass ``ModelChoiceField`` and override
    
  1349.     ``label_from_instance``. This method will receive a model object and should
    
  1350.     return a string suitable for representing it. For example::
    
  1351. 
    
  1352.         from django.forms import ModelChoiceField
    
  1353. 
    
  1354.         class MyModelChoiceField(ModelChoiceField):
    
  1355.             def label_from_instance(self, obj):
    
  1356.                 return "My Object #%i" % obj.id
    
  1357. 
    
  1358.     .. versionchanged:: 4.0
    
  1359. 
    
  1360.         Support for containing ``%(value)s`` in the ``invalid_choice`` error
    
  1361.         message was added.
    
  1362. 
    
  1363. ``ModelMultipleChoiceField``
    
  1364. ----------------------------
    
  1365. 
    
  1366. .. class:: ModelMultipleChoiceField(**kwargs)
    
  1367. 
    
  1368.     * Default widget: :class:`SelectMultiple`
    
  1369.     * Empty value: An empty ``QuerySet`` (``self.queryset.none()``)
    
  1370.     * Normalizes to: A ``QuerySet`` of model instances.
    
  1371.     * Validates that every id in the given list of values exists in the
    
  1372.       queryset.
    
  1373.     * Error message keys: ``required``, ``invalid_list``, ``invalid_choice``,
    
  1374.       ``invalid_pk_value``
    
  1375. 
    
  1376.     The ``invalid_choice`` message may contain ``%(value)s`` and the
    
  1377.     ``invalid_pk_value`` message may contain ``%(pk)s``, which will be
    
  1378.     substituted by the appropriate values.
    
  1379. 
    
  1380.     Allows the selection of one or more model objects, suitable for
    
  1381.     representing a many-to-many relation. As with :class:`ModelChoiceField`,
    
  1382.     you can use ``label_from_instance`` to customize the object
    
  1383.     representations.
    
  1384. 
    
  1385.     A single argument is required:
    
  1386. 
    
  1387.     .. attribute:: queryset
    
  1388. 
    
  1389.         Same as :class:`ModelChoiceField.queryset`.
    
  1390. 
    
  1391.     Takes one optional argument:
    
  1392. 
    
  1393.     .. attribute:: to_field_name
    
  1394. 
    
  1395.         Same as :class:`ModelChoiceField.to_field_name`.
    
  1396. 
    
  1397.     ``ModelMultipleChoiceField`` also has the attribute:
    
  1398. 
    
  1399.     .. attribute:: iterator
    
  1400. 
    
  1401.         Same as :class:`ModelChoiceField.iterator`.
    
  1402. 
    
  1403. .. _iterating-relationship-choices:
    
  1404. 
    
  1405. Iterating relationship choices
    
  1406. ------------------------------
    
  1407. 
    
  1408. By default, :class:`ModelChoiceField` and :class:`ModelMultipleChoiceField` use
    
  1409. :class:`ModelChoiceIterator` to generate their field ``choices``.
    
  1410. 
    
  1411. When iterated, ``ModelChoiceIterator`` yields 2-tuple choices containing
    
  1412. :class:`ModelChoiceIteratorValue` instances as the first ``value`` element in
    
  1413. each choice. ``ModelChoiceIteratorValue`` wraps the choice value while
    
  1414. maintaining a reference to the source model instance that can be used in custom
    
  1415. widget implementations, for example, to add `data-* attributes`_ to
    
  1416. ``<option>`` elements.
    
  1417. 
    
  1418. .. _`data-* attributes`: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*
    
  1419. 
    
  1420. For example, consider the following models::
    
  1421. 
    
  1422.     from django.db import models
    
  1423. 
    
  1424.     class Topping(models.Model):
    
  1425.         name = models.CharField(max_length=100)
    
  1426.         price = models.DecimalField(decimal_places=2, max_digits=6)
    
  1427. 
    
  1428.         def __str__(self):
    
  1429.             return self.name
    
  1430. 
    
  1431.     class Pizza(models.Model):
    
  1432.         topping = models.ForeignKey(Topping, on_delete=models.CASCADE)
    
  1433. 
    
  1434. You can use a :class:`~django.forms.Select` widget subclass to include
    
  1435. the value of ``Topping.price`` as the HTML attribute ``data-price`` for each
    
  1436. ``<option>`` element::
    
  1437. 
    
  1438.     from django import forms
    
  1439. 
    
  1440.     class ToppingSelect(forms.Select):
    
  1441.         def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
    
  1442.             option = super().create_option(name, value, label, selected, index, subindex, attrs)
    
  1443.             if value:
    
  1444.                 option['attrs']['data-price'] = value.instance.price
    
  1445.             return option
    
  1446. 
    
  1447.     class PizzaForm(forms.ModelForm):
    
  1448.         class Meta:
    
  1449.             model = Pizza
    
  1450.             fields = ['topping']
    
  1451.             widgets = {'topping': ToppingSelect}
    
  1452. 
    
  1453. This will render the ``Pizza.topping`` select as:
    
  1454. 
    
  1455. .. code-block:: html
    
  1456. 
    
  1457.     <select id="id_topping" name="topping" required>
    
  1458.     <option value="" selected>---------</option>
    
  1459.     <option value="1" data-price="1.50">mushrooms</option>
    
  1460.     <option value="2" data-price="1.25">onions</option>
    
  1461.     <option value="3" data-price="1.75">peppers</option>
    
  1462.     <option value="4" data-price="2.00">pineapple</option>
    
  1463.     </select>
    
  1464. 
    
  1465. For more advanced usage you may subclass ``ModelChoiceIterator`` in order to
    
  1466. customize the yielded 2-tuple choices.
    
  1467. 
    
  1468. ``ModelChoiceIterator``
    
  1469. ~~~~~~~~~~~~~~~~~~~~~~~
    
  1470. 
    
  1471. .. class:: ModelChoiceIterator(field)
    
  1472. 
    
  1473.     The default class assigned to the ``iterator`` attribute of
    
  1474.     :class:`ModelChoiceField` and :class:`ModelMultipleChoiceField`. An
    
  1475.     iterable that yields 2-tuple choices from the queryset.
    
  1476. 
    
  1477.     A single argument is required:
    
  1478. 
    
  1479.     .. attribute:: field
    
  1480. 
    
  1481.         The instance of ``ModelChoiceField`` or ``ModelMultipleChoiceField`` to
    
  1482.         iterate and yield choices.
    
  1483. 
    
  1484.     ``ModelChoiceIterator`` has the following method:
    
  1485. 
    
  1486.     .. method:: __iter__()
    
  1487. 
    
  1488.         Yields 2-tuple choices, in the ``(value, label)`` format used by
    
  1489.         :attr:`ChoiceField.choices`. The first ``value`` element is a
    
  1490.         :class:`ModelChoiceIteratorValue` instance.
    
  1491. 
    
  1492. ``ModelChoiceIteratorValue``
    
  1493. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  1494. 
    
  1495. .. class:: ModelChoiceIteratorValue(value, instance)
    
  1496. 
    
  1497.     Two arguments are required:
    
  1498. 
    
  1499.     .. attribute:: value
    
  1500. 
    
  1501.         The value of the choice. This value is used to render the ``value``
    
  1502.         attribute of an HTML ``<option>`` element.
    
  1503. 
    
  1504.     .. attribute:: instance
    
  1505. 
    
  1506.         The model instance from the queryset. The instance can be accessed in
    
  1507.         custom ``ChoiceWidget.create_option()`` implementations to adjust the
    
  1508.         rendered HTML.
    
  1509. 
    
  1510.     ``ModelChoiceIteratorValue`` has the following method:
    
  1511. 
    
  1512.     .. method:: __str__()
    
  1513. 
    
  1514.         Return ``value`` as a string to be rendered in HTML.
    
  1515. 
    
  1516. Creating custom fields
    
  1517. ======================
    
  1518. 
    
  1519. If the built-in ``Field`` classes don't meet your needs, you can create custom
    
  1520. ``Field`` classes. To do this, create a subclass of ``django.forms.Field``. Its
    
  1521. only requirements are that it implement a ``clean()`` method and that its
    
  1522. ``__init__()`` method accept the core arguments mentioned above (``required``,
    
  1523. ``label``, ``initial``, ``widget``, ``help_text``).
    
  1524. 
    
  1525. You can also customize how a field will be accessed by overriding
    
  1526. :meth:`~django.forms.Field.get_bound_field()`.