1. =============
    
  2. The Forms API
    
  3. =============
    
  4. 
    
  5. .. module:: django.forms
    
  6. 
    
  7. .. admonition:: About this document
    
  8. 
    
  9.     This document covers the gritty details of Django's forms API. You should
    
  10.     read the :doc:`introduction to working with forms </topics/forms/index>`
    
  11.     first.
    
  12. 
    
  13. .. _ref-forms-api-bound-unbound:
    
  14. 
    
  15. Bound and unbound forms
    
  16. =======================
    
  17. 
    
  18. A :class:`Form` instance is either **bound** to a set of data, or **unbound**.
    
  19. 
    
  20. * If it's **bound** to a set of data, it's capable of validating that data
    
  21.   and rendering the form as HTML with the data displayed in the HTML.
    
  22. 
    
  23. * If it's **unbound**, it cannot do validation (because there's no data to
    
  24.   validate!), but it can still render the blank form as HTML.
    
  25. 
    
  26. .. class:: Form
    
  27. 
    
  28. To create an unbound :class:`Form` instance, instantiate the class::
    
  29. 
    
  30.     >>> f = ContactForm()
    
  31. 
    
  32. To bind data to a form, pass the data as a dictionary as the first parameter to
    
  33. your :class:`Form` class constructor::
    
  34. 
    
  35.     >>> data = {'subject': 'hello',
    
  36.     ...         'message': 'Hi there',
    
  37.     ...         'sender': '[email protected]',
    
  38.     ...         'cc_myself': True}
    
  39.     >>> f = ContactForm(data)
    
  40. 
    
  41. In this dictionary, the keys are the field names, which correspond to the
    
  42. attributes in your :class:`Form` class. The values are the data you're trying to
    
  43. validate. These will usually be strings, but there's no requirement that they be
    
  44. strings; the type of data you pass depends on the :class:`Field`, as we'll see
    
  45. in a moment.
    
  46. 
    
  47. .. attribute:: Form.is_bound
    
  48. 
    
  49. If you need to distinguish between bound and unbound form instances at runtime,
    
  50. check the value of the form's :attr:`~Form.is_bound` attribute::
    
  51. 
    
  52.     >>> f = ContactForm()
    
  53.     >>> f.is_bound
    
  54.     False
    
  55.     >>> f = ContactForm({'subject': 'hello'})
    
  56.     >>> f.is_bound
    
  57.     True
    
  58. 
    
  59. Note that passing an empty dictionary creates a *bound* form with empty data::
    
  60. 
    
  61.     >>> f = ContactForm({})
    
  62.     >>> f.is_bound
    
  63.     True
    
  64. 
    
  65. If you have a bound :class:`Form` instance and want to change the data somehow,
    
  66. or if you want to bind an unbound :class:`Form` instance to some data, create
    
  67. another :class:`Form` instance. There is no way to change data in a
    
  68. :class:`Form` instance. Once a :class:`Form` instance has been created, you
    
  69. should consider its data immutable, whether it has data or not.
    
  70. 
    
  71. Using forms to validate data
    
  72. ============================
    
  73. 
    
  74. .. method:: Form.clean()
    
  75. 
    
  76. Implement a ``clean()`` method on your ``Form`` when you must add custom
    
  77. validation for fields that are interdependent. See
    
  78. :ref:`validating-fields-with-clean` for example usage.
    
  79. 
    
  80. .. method:: Form.is_valid()
    
  81. 
    
  82. The primary task of a :class:`Form` object is to validate data. With a bound
    
  83. :class:`Form` instance, call the :meth:`~Form.is_valid` method to run validation
    
  84. and return a boolean designating whether the data was valid::
    
  85. 
    
  86.     >>> data = {'subject': 'hello',
    
  87.     ...         'message': 'Hi there',
    
  88.     ...         'sender': '[email protected]',
    
  89.     ...         'cc_myself': True}
    
  90.     >>> f = ContactForm(data)
    
  91.     >>> f.is_valid()
    
  92.     True
    
  93. 
    
  94. Let's try with some invalid data. In this case, ``subject`` is blank (an error,
    
  95. because all fields are required by default) and ``sender`` is not a valid
    
  96. email address::
    
  97. 
    
  98.     >>> data = {'subject': '',
    
  99.     ...         'message': 'Hi there',
    
  100.     ...         'sender': 'invalid email address',
    
  101.     ...         'cc_myself': True}
    
  102.     >>> f = ContactForm(data)
    
  103.     >>> f.is_valid()
    
  104.     False
    
  105. 
    
  106. .. attribute:: Form.errors
    
  107. 
    
  108. Access the :attr:`~Form.errors` attribute to get a dictionary of error
    
  109. messages::
    
  110. 
    
  111.     >>> f.errors
    
  112.     {'sender': ['Enter a valid email address.'], 'subject': ['This field is required.']}
    
  113. 
    
  114. In this dictionary, the keys are the field names, and the values are lists of
    
  115. strings representing the error messages. The error messages are stored
    
  116. in lists because a field can have multiple error messages.
    
  117. 
    
  118. You can access :attr:`~Form.errors` without having to call
    
  119. :meth:`~Form.is_valid` first. The form's data will be validated the first time
    
  120. either you call :meth:`~Form.is_valid` or access :attr:`~Form.errors`.
    
  121. 
    
  122. The validation routines will only get called once, regardless of how many times
    
  123. you access :attr:`~Form.errors` or call :meth:`~Form.is_valid`. This means that
    
  124. if validation has side effects, those side effects will only be triggered once.
    
  125. 
    
  126. .. method:: Form.errors.as_data()
    
  127. 
    
  128. Returns a ``dict`` that maps fields to their original ``ValidationError``
    
  129. instances.
    
  130. 
    
  131.     >>> f.errors.as_data()
    
  132.     {'sender': [ValidationError(['Enter a valid email address.'])],
    
  133.     'subject': [ValidationError(['This field is required.'])]}
    
  134. 
    
  135. Use this method anytime you need to identify an error by its ``code``. This
    
  136. enables things like rewriting the error's message or writing custom logic in a
    
  137. view when a given error is present. It can also be used to serialize the errors
    
  138. in a custom format (e.g. XML); for instance, :meth:`~Form.errors.as_json()`
    
  139. relies on ``as_data()``.
    
  140. 
    
  141. The need for the ``as_data()`` method is due to backwards compatibility.
    
  142. Previously ``ValidationError`` instances were lost as soon as their
    
  143. **rendered** error messages were added to the ``Form.errors`` dictionary.
    
  144. Ideally ``Form.errors`` would have stored ``ValidationError`` instances
    
  145. and methods with an ``as_`` prefix could render them, but it had to be done
    
  146. the other way around in order not to break code that expects rendered error
    
  147. messages in ``Form.errors``.
    
  148. 
    
  149. .. method:: Form.errors.as_json(escape_html=False)
    
  150. 
    
  151. Returns the errors serialized as JSON.
    
  152. 
    
  153.     >>> f.errors.as_json()
    
  154.     {"sender": [{"message": "Enter a valid email address.", "code": "invalid"}],
    
  155.     "subject": [{"message": "This field is required.", "code": "required"}]}
    
  156. 
    
  157. By default, ``as_json()`` does not escape its output. If you are using it for
    
  158. something like AJAX requests to a form view where the client interprets the
    
  159. response and inserts errors into the page, you'll want to be sure to escape the
    
  160. results on the client-side to avoid the possibility of a cross-site scripting
    
  161. attack. You can do this in JavaScript with ``element.textContent = errorText``
    
  162. or with jQuery's ``$(el).text(errorText)`` (rather than its ``.html()``
    
  163. function).
    
  164. 
    
  165. If for some reason you don't want to use client-side escaping, you can also
    
  166. set ``escape_html=True`` and error messages will be escaped so you can use them
    
  167. directly in HTML.
    
  168. 
    
  169. .. method:: Form.errors.get_json_data(escape_html=False)
    
  170. 
    
  171. Returns the errors as a dictionary suitable for serializing to JSON.
    
  172. :meth:`Form.errors.as_json()` returns serialized JSON, while this returns the
    
  173. error data before it's serialized.
    
  174. 
    
  175. The ``escape_html`` parameter behaves as described in
    
  176. :meth:`Form.errors.as_json()`.
    
  177. 
    
  178. .. method:: Form.add_error(field, error)
    
  179. 
    
  180. This method allows adding errors to specific fields from within the
    
  181. ``Form.clean()`` method, or from outside the form altogether; for instance
    
  182. from a view.
    
  183. 
    
  184. The ``field`` argument is the name of the field to which the errors
    
  185. should be added. If its value is ``None`` the error will be treated as
    
  186. a non-field error as returned by :meth:`Form.non_field_errors()
    
  187. <django.forms.Form.non_field_errors>`.
    
  188. 
    
  189. The ``error`` argument can be a string, or preferably an instance of
    
  190. ``ValidationError``. See :ref:`raising-validation-error` for best practices
    
  191. when defining form errors.
    
  192. 
    
  193. Note that ``Form.add_error()`` automatically removes the relevant field from
    
  194. ``cleaned_data``.
    
  195. 
    
  196. .. method:: Form.has_error(field, code=None)
    
  197. 
    
  198. This method returns a boolean designating whether a field has an error with
    
  199. a specific error ``code``. If ``code`` is ``None``, it will return ``True``
    
  200. if the field contains any errors at all.
    
  201. 
    
  202. To check for non-field errors use
    
  203. :data:`~django.core.exceptions.NON_FIELD_ERRORS` as the ``field`` parameter.
    
  204. 
    
  205. .. method:: Form.non_field_errors()
    
  206. 
    
  207. This method returns the list of errors from :attr:`Form.errors
    
  208. <django.forms.Form.errors>`  that aren't associated with a particular field.
    
  209. This includes ``ValidationError``\s that are raised in :meth:`Form.clean()
    
  210. <django.forms.Form.clean>` and errors added using :meth:`Form.add_error(None,
    
  211. "...") <django.forms.Form.add_error>`.
    
  212. 
    
  213. Behavior of unbound forms
    
  214. -------------------------
    
  215. 
    
  216. It's meaningless to validate a form with no data, but, for the record, here's
    
  217. what happens with unbound forms::
    
  218. 
    
  219.     >>> f = ContactForm()
    
  220.     >>> f.is_valid()
    
  221.     False
    
  222.     >>> f.errors
    
  223.     {}
    
  224. 
    
  225. .. _ref-forms-initial-form-values:
    
  226. 
    
  227. Initial form values
    
  228. ===================
    
  229. 
    
  230. .. attribute:: Form.initial
    
  231. 
    
  232. Use :attr:`~Form.initial` to declare the initial value of form fields at
    
  233. runtime. For example, you might want to fill in a ``username`` field with the
    
  234. username of the current session.
    
  235. 
    
  236. To accomplish this, use the :attr:`~Form.initial` argument to a :class:`Form`.
    
  237. This argument, if given, should be a dictionary mapping field names to initial
    
  238. values. Only include the fields for which you're specifying an initial value;
    
  239. it's not necessary to include every field in your form. For example::
    
  240. 
    
  241.     >>> f = ContactForm(initial={'subject': 'Hi there!'})
    
  242. 
    
  243. These values are only displayed for unbound forms, and they're not used as
    
  244. fallback values if a particular value isn't provided.
    
  245. 
    
  246. If a :class:`~django.forms.Field` defines :attr:`~Field.initial` *and* you
    
  247. include :attr:`~Form.initial` when instantiating the ``Form``, then the latter
    
  248. ``initial`` will have precedence. In this example, ``initial`` is provided both
    
  249. at the field level and at the form instance level, and the latter gets
    
  250. precedence::
    
  251. 
    
  252.     >>> from django import forms
    
  253.     >>> class CommentForm(forms.Form):
    
  254.     ...     name = forms.CharField(initial='class')
    
  255.     ...     url = forms.URLField()
    
  256.     ...     comment = forms.CharField()
    
  257.     >>> f = CommentForm(initial={'name': 'instance'}, auto_id=False)
    
  258.     >>> print(f)
    
  259.     <tr><th>Name:</th><td><input type="text" name="name" value="instance" required></td></tr>
    
  260.     <tr><th>Url:</th><td><input type="url" name="url" required></td></tr>
    
  261.     <tr><th>Comment:</th><td><input type="text" name="comment" required></td></tr>
    
  262. 
    
  263. .. method:: Form.get_initial_for_field(field, field_name)
    
  264. 
    
  265. Returns the initial data for a form field. It retrieves the data from
    
  266. :attr:`Form.initial` if present, otherwise trying :attr:`Field.initial`.
    
  267. Callable values are evaluated.
    
  268. 
    
  269. It is recommended to use :attr:`BoundField.initial` over
    
  270. :meth:`~Form.get_initial_for_field()` because ``BoundField.initial`` has a
    
  271. simpler interface. Also, unlike :meth:`~Form.get_initial_for_field()`,
    
  272. :attr:`BoundField.initial` caches its values. This is useful especially when
    
  273. dealing with callables whose return values can change (e.g. ``datetime.now`` or
    
  274. ``uuid.uuid4``)::
    
  275. 
    
  276.     >>> import uuid
    
  277.     >>> class UUIDCommentForm(CommentForm):
    
  278.     ...     identifier = forms.UUIDField(initial=uuid.uuid4)
    
  279.     >>> f = UUIDCommentForm()
    
  280.     >>> f.get_initial_for_field(f.fields['identifier'], 'identifier')
    
  281.     UUID('972ca9e4-7bfe-4f5b-af7d-07b3aa306334')
    
  282.     >>> f.get_initial_for_field(f.fields['identifier'], 'identifier')
    
  283.     UUID('1b411fab-844e-4dec-bd4f-e9b0495f04d0')
    
  284.     >>> # Using BoundField.initial, for comparison
    
  285.     >>> f['identifier'].initial
    
  286.     UUID('28a09c59-5f00-4ed9-9179-a3b074fa9c30')
    
  287.     >>> f['identifier'].initial
    
  288.     UUID('28a09c59-5f00-4ed9-9179-a3b074fa9c30')
    
  289. 
    
  290. Checking which form data has changed
    
  291. ====================================
    
  292. 
    
  293. .. method:: Form.has_changed()
    
  294. 
    
  295. Use the ``has_changed()`` method on your ``Form`` when you need to check if the
    
  296. form data has been changed from the initial data.
    
  297. 
    
  298.     >>> data = {'subject': 'hello',
    
  299.     ...         'message': 'Hi there',
    
  300.     ...         'sender': '[email protected]',
    
  301.     ...         'cc_myself': True}
    
  302.     >>> f = ContactForm(data, initial=data)
    
  303.     >>> f.has_changed()
    
  304.     False
    
  305. 
    
  306. When the form is submitted, we reconstruct it and provide the original data
    
  307. so that the comparison can be done:
    
  308. 
    
  309.     >>> f = ContactForm(request.POST, initial=data)
    
  310.     >>> f.has_changed()
    
  311. 
    
  312. ``has_changed()`` will be ``True`` if the data from ``request.POST`` differs
    
  313. from what was provided in :attr:`~Form.initial` or ``False`` otherwise. The
    
  314. result is computed by calling :meth:`Field.has_changed` for each field in the
    
  315. form.
    
  316. 
    
  317. .. attribute:: Form.changed_data
    
  318. 
    
  319. The ``changed_data`` attribute returns a list of the names of the fields whose
    
  320. values in the form's bound data (usually ``request.POST``) differ from what was
    
  321. provided in :attr:`~Form.initial`. It returns an empty list if no data differs.
    
  322. 
    
  323.     >>> f = ContactForm(request.POST, initial=data)
    
  324.     >>> if f.has_changed():
    
  325.     ...     print("The following fields changed: %s" % ", ".join(f.changed_data))
    
  326.     >>> f.changed_data
    
  327.     ['subject', 'message']
    
  328. 
    
  329. Accessing the fields from the form
    
  330. ==================================
    
  331. 
    
  332. .. attribute:: Form.fields
    
  333. 
    
  334. You can access the fields of :class:`Form` instance from its ``fields``
    
  335. attribute::
    
  336. 
    
  337.     >>> for row in f.fields.values(): print(row)
    
  338.     ...
    
  339.     <django.forms.fields.CharField object at 0x7ffaac632510>
    
  340.     <django.forms.fields.URLField object at 0x7ffaac632f90>
    
  341.     <django.forms.fields.CharField object at 0x7ffaac3aa050>
    
  342.     >>> f.fields['name']
    
  343.     <django.forms.fields.CharField object at 0x7ffaac6324d0>
    
  344. 
    
  345. You can alter the field and :class:`.BoundField` of :class:`Form` instance to
    
  346. change the way it is presented in the form::
    
  347. 
    
  348.     >>> f.as_div().split("</div>")[0]
    
  349.     '<div><label for="id_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_subject">'
    
  350.     >>> f["subject"].label = "Topic"
    
  351.     >>> f.as_div().split("</div>")[0]
    
  352.     '<div><label for="id_subject">Topic:</label><input type="text" name="subject" maxlength="100" required id="id_subject">'
    
  353. 
    
  354. Beware not to alter the ``base_fields`` attribute because this modification
    
  355. will influence all subsequent ``ContactForm`` instances within the same Python
    
  356. process::
    
  357. 
    
  358.     >>> f.base_fields["subject"].label_suffix = "?"
    
  359.     >>> another_f = CommentForm(auto_id=False)
    
  360.     >>> f.as_div().split("</div>")[0]
    
  361.     '<div><label for="id_subject">Subject?</label><input type="text" name="subject" maxlength="100" required id="id_subject">'
    
  362. 
    
  363. Accessing "clean" data
    
  364. ======================
    
  365. 
    
  366. .. attribute:: Form.cleaned_data
    
  367. 
    
  368. Each field in a :class:`Form` class is responsible not only for validating
    
  369. data, but also for "cleaning" it -- normalizing it to a consistent format. This
    
  370. is a nice feature, because it allows data for a particular field to be input in
    
  371. a variety of ways, always resulting in consistent output.
    
  372. 
    
  373. For example, :class:`~django.forms.DateField` normalizes input into a
    
  374. Python ``datetime.date`` object. Regardless of whether you pass it a string in
    
  375. the format ``'1994-07-15'``, a ``datetime.date`` object, or a number of other
    
  376. formats, ``DateField`` will always normalize it to a ``datetime.date`` object
    
  377. as long as it's valid.
    
  378. 
    
  379. Once you've created a :class:`~Form` instance with a set of data and validated
    
  380. it, you can access the clean data via its ``cleaned_data`` attribute::
    
  381. 
    
  382.     >>> data = {'subject': 'hello',
    
  383.     ...         'message': 'Hi there',
    
  384.     ...         'sender': '[email protected]',
    
  385.     ...         'cc_myself': True}
    
  386.     >>> f = ContactForm(data)
    
  387.     >>> f.is_valid()
    
  388.     True
    
  389.     >>> f.cleaned_data
    
  390.     {'cc_myself': True, 'message': 'Hi there', 'sender': '[email protected]', 'subject': 'hello'}
    
  391. 
    
  392. Note that any text-based field -- such as ``CharField`` or ``EmailField`` --
    
  393. always cleans the input into a string. We'll cover the encoding implications
    
  394. later in this document.
    
  395. 
    
  396. If your data does *not* validate, the ``cleaned_data`` dictionary contains
    
  397. only the valid fields::
    
  398. 
    
  399.     >>> data = {'subject': '',
    
  400.     ...         'message': 'Hi there',
    
  401.     ...         'sender': 'invalid email address',
    
  402.     ...         'cc_myself': True}
    
  403.     >>> f = ContactForm(data)
    
  404.     >>> f.is_valid()
    
  405.     False
    
  406.     >>> f.cleaned_data
    
  407.     {'cc_myself': True, 'message': 'Hi there'}
    
  408. 
    
  409. ``cleaned_data`` will always *only* contain a key for fields defined in the
    
  410. ``Form``, even if you pass extra data when you define the ``Form``. In this
    
  411. example, we pass a bunch of extra fields to the ``ContactForm`` constructor,
    
  412. but ``cleaned_data`` contains only the form's fields::
    
  413. 
    
  414.     >>> data = {'subject': 'hello',
    
  415.     ...         'message': 'Hi there',
    
  416.     ...         'sender': '[email protected]',
    
  417.     ...         'cc_myself': True,
    
  418.     ...         'extra_field_1': 'foo',
    
  419.     ...         'extra_field_2': 'bar',
    
  420.     ...         'extra_field_3': 'baz'}
    
  421.     >>> f = ContactForm(data)
    
  422.     >>> f.is_valid()
    
  423.     True
    
  424.     >>> f.cleaned_data # Doesn't contain extra_field_1, etc.
    
  425.     {'cc_myself': True, 'message': 'Hi there', 'sender': '[email protected]', 'subject': 'hello'}
    
  426. 
    
  427. When the ``Form`` is valid, ``cleaned_data`` will include a key and value for
    
  428. *all* its fields, even if the data didn't include a value for some optional
    
  429. fields. In this example, the data dictionary doesn't include a value for the
    
  430. ``nick_name`` field, but ``cleaned_data`` includes it, with an empty value::
    
  431. 
    
  432.     >>> from django import forms
    
  433.     >>> class OptionalPersonForm(forms.Form):
    
  434.     ...     first_name = forms.CharField()
    
  435.     ...     last_name = forms.CharField()
    
  436.     ...     nick_name = forms.CharField(required=False)
    
  437.     >>> data = {'first_name': 'John', 'last_name': 'Lennon'}
    
  438.     >>> f = OptionalPersonForm(data)
    
  439.     >>> f.is_valid()
    
  440.     True
    
  441.     >>> f.cleaned_data
    
  442.     {'nick_name': '', 'first_name': 'John', 'last_name': 'Lennon'}
    
  443. 
    
  444. In this above example, the ``cleaned_data`` value for ``nick_name`` is set to an
    
  445. empty string, because ``nick_name`` is ``CharField``, and ``CharField``\s treat
    
  446. empty values as an empty string. Each field type knows what its "blank" value
    
  447. is -- e.g., for ``DateField``, it's ``None`` instead of the empty string. For
    
  448. full details on each field's behavior in this case, see the "Empty value" note
    
  449. for each field in the "Built-in ``Field`` classes" section below.
    
  450. 
    
  451. You can write code to perform validation for particular form fields (based on
    
  452. their name) or for the form as a whole (considering combinations of various
    
  453. fields). More information about this is in :doc:`/ref/forms/validation`.
    
  454. 
    
  455. .. _ref-forms-api-outputting-html:
    
  456. 
    
  457. Outputting forms as HTML
    
  458. ========================
    
  459. 
    
  460. The second task of a ``Form`` object is to render itself as HTML. To do so,
    
  461. ``print`` it::
    
  462. 
    
  463.     >>> f = ContactForm()
    
  464.     >>> print(f)
    
  465.     <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr>
    
  466.     <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr>
    
  467.     <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr>
    
  468.     <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr>
    
  469. 
    
  470. If the form is bound to data, the HTML output will include that data
    
  471. appropriately. For example, if a field is represented by an
    
  472. ``<input type="text">``, the data will be in the ``value`` attribute. If a
    
  473. field is represented by an ``<input type="checkbox">``, then that HTML will
    
  474. include ``checked`` if appropriate::
    
  475. 
    
  476.     >>> data = {'subject': 'hello',
    
  477.     ...         'message': 'Hi there',
    
  478.     ...         'sender': '[email protected]',
    
  479.     ...         'cc_myself': True}
    
  480.     >>> f = ContactForm(data)
    
  481.     >>> print(f)
    
  482.     <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" value="hello" required></td></tr>
    
  483.     <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" value="Hi there" required></td></tr>
    
  484.     <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" value="[email protected]" required></td></tr>
    
  485.     <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" checked></td></tr>
    
  486. 
    
  487. This default output is a two-column HTML table, with a ``<tr>`` for each field.
    
  488. Notice the following:
    
  489. 
    
  490. * For flexibility, the output does *not* include the ``<table>`` and
    
  491.   ``</table>`` tags, nor does it include the ``<form>`` and ``</form>``
    
  492.   tags or an ``<input type="submit">`` tag. It's your job to do that.
    
  493. 
    
  494. * Each field type has a default HTML representation. ``CharField`` is
    
  495.   represented by an ``<input type="text">`` and ``EmailField`` by an
    
  496.   ``<input type="email">``. ``BooleanField(null=False)`` is represented by an
    
  497.   ``<input type="checkbox">``. Note these are merely sensible defaults; you can
    
  498.   specify which HTML to use for a given field by using widgets, which we'll
    
  499.   explain shortly.
    
  500. 
    
  501. * The HTML ``name`` for each tag is taken directly from its attribute name
    
  502.   in the ``ContactForm`` class.
    
  503. 
    
  504. * The text label for each field -- e.g. ``'Subject:'``, ``'Message:'`` and
    
  505.   ``'Cc myself:'`` is generated from the field name by converting all
    
  506.   underscores to spaces and upper-casing the first letter. Again, note
    
  507.   these are merely sensible defaults; you can also specify labels manually.
    
  508. 
    
  509. * Each text label is surrounded in an HTML ``<label>`` tag, which points
    
  510.   to the appropriate form field via its ``id``. Its ``id``, in turn, is
    
  511.   generated by prepending ``'id_'`` to the field name. The ``id``
    
  512.   attributes and ``<label>`` tags are included in the output by default, to
    
  513.   follow best practices, but you can change that behavior.
    
  514. 
    
  515. * The output uses HTML5 syntax, targeting ``<!DOCTYPE html>``. For example,
    
  516.   it uses boolean attributes such as ``checked`` rather than the XHTML style
    
  517.   of ``checked='checked'``.
    
  518. 
    
  519. Although ``<table>`` output is the default output style when you ``print`` a
    
  520. form, other output styles are available. Each style is available as a method on
    
  521. a form object, and each rendering method returns a string.
    
  522. 
    
  523. Default rendering
    
  524. -----------------
    
  525. 
    
  526. The default rendering when you ``print`` a form uses the following methods and
    
  527. attributes.
    
  528. 
    
  529. ``template_name``
    
  530. ~~~~~~~~~~~~~~~~~
    
  531. 
    
  532. .. versionadded:: 4.0
    
  533. 
    
  534. .. attribute:: Form.template_name
    
  535. 
    
  536. The name of the template rendered if the form is cast into a string, e.g. via
    
  537. ``print(form)`` or in a template via ``{{ form }}``.
    
  538. 
    
  539. By default, a property returning the value of the renderer's
    
  540. :attr:`~django.forms.renderers.BaseRenderer.form_template_name`. You may set it
    
  541. as a string template name in order to override that for a particular form
    
  542. class.
    
  543. 
    
  544. .. versionchanged:: 4.1
    
  545. 
    
  546.     In older versions ``template_name`` defaulted to the string value
    
  547.     ``'django/forms/default.html'``.
    
  548. 
    
  549. ``render()``
    
  550. ~~~~~~~~~~~~
    
  551. 
    
  552. .. versionadded:: 4.0
    
  553. 
    
  554. .. method:: Form.render(template_name=None, context=None, renderer=None)
    
  555. 
    
  556. The render method is called by ``__str__`` as well as the
    
  557. :meth:`.Form.as_table`, :meth:`.Form.as_p`, and :meth:`.Form.as_ul` methods.
    
  558. All arguments are optional and default to:
    
  559. 
    
  560. * ``template_name``: :attr:`.Form.template_name`
    
  561. * ``context``: Value returned by :meth:`.Form.get_context`
    
  562. * ``renderer``: Value returned by :attr:`.Form.default_renderer`
    
  563. 
    
  564. By passing ``template_name`` you can customize the template used for just a
    
  565. single call.
    
  566. 
    
  567. ``get_context()``
    
  568. ~~~~~~~~~~~~~~~~~
    
  569. 
    
  570. .. versionadded:: 4.0
    
  571. 
    
  572. .. method:: Form.get_context()
    
  573. 
    
  574. Return the template context for rendering the form.
    
  575. 
    
  576. The available context is:
    
  577. 
    
  578. * ``form``: The bound form.
    
  579. * ``fields``: All bound fields, except the hidden fields.
    
  580. * ``hidden_fields``: All hidden bound fields.
    
  581. * ``errors``: All non field related or hidden field related form errors.
    
  582. 
    
  583. ``template_name_label``
    
  584. ~~~~~~~~~~~~~~~~~~~~~~~
    
  585. 
    
  586. .. versionadded:: 4.0
    
  587. 
    
  588. .. attribute:: Form.template_name_label
    
  589. 
    
  590. The template used to render a field's ``<label>``, used when calling
    
  591. :meth:`BoundField.label_tag`/:meth:`~BoundField.legend_tag`. Can be changed per
    
  592. form by overriding this attribute or more generally by overriding the default
    
  593. template, see also :ref:`overriding-built-in-form-templates`.
    
  594. 
    
  595. Output styles
    
  596. -------------
    
  597. 
    
  598. As well as rendering the form directly, such as in a template with
    
  599. ``{{ form }}``, the following helper functions serve as a proxy to
    
  600. :meth:`Form.render` passing a particular ``template_name`` value.
    
  601. 
    
  602. These helpers are most useful in a template, where you need to override the
    
  603. form renderer or form provided value but cannot pass the additional parameter
    
  604. to :meth:`~Form.render`. For example, you can render a form as an unordered
    
  605. list using ``{{ form.as_ul }}``.
    
  606. 
    
  607. Each helper pairs a form method with an attribute giving the appropriate
    
  608. template name.
    
  609. 
    
  610. ``as_div()``
    
  611. ~~~~~~~~~~~~
    
  612. 
    
  613. .. attribute:: Form.template_name_div
    
  614. 
    
  615. .. versionadded:: 4.1
    
  616. 
    
  617. The template used by ``as_div()``. Default: ``'django/forms/div.html'``.
    
  618. 
    
  619. .. method:: Form.as_div()
    
  620. 
    
  621. .. versionadded:: 4.1
    
  622. 
    
  623. ``as_div()`` renders the form as a series of ``<div>`` elements, with each
    
  624. ``<div>`` containing one field, such as:
    
  625. 
    
  626. .. code-block:: pycon
    
  627. 
    
  628.     >>> f = ContactForm()
    
  629.     >>> f.as_div()
    
  630. 
    
  631. … gives HTML like:
    
  632. 
    
  633. .. code-block:: html
    
  634. 
    
  635.     <div>
    
  636.     <label for="id_subject">Subject:</label>
    
  637.     <input type="text" name="subject" maxlength="100" required id="id_subject">
    
  638.     </div>
    
  639.     <div>
    
  640.     <label for="id_message">Message:</label>
    
  641.     <input type="text" name="message" required id="id_message">
    
  642.     </div>
    
  643.     <div>
    
  644.     <label for="id_sender">Sender:</label>
    
  645.     <input type="email" name="sender" required id="id_sender">
    
  646.     </div>
    
  647.     <div>
    
  648.     <label for="id_cc_myself">Cc myself:</label>
    
  649.     <input type="checkbox" name="cc_myself" id="id_cc_myself">
    
  650.     </div>
    
  651. 
    
  652. .. note::
    
  653. 
    
  654.     Of the framework provided templates and output styles, ``as_div()`` is
    
  655.     recommended over the ``as_p()``, ``as_table()``, and ``as_ul()`` versions
    
  656.     as the template implements ``<fieldset>`` and ``<legend>`` to group related
    
  657.     inputs and is easier for screen reader users to navigate.
    
  658. 
    
  659. ``as_p()``
    
  660. ~~~~~~~~~~
    
  661. 
    
  662. .. attribute:: Form.template_name_p
    
  663. 
    
  664. The template used by ``as_p()``. Default: ``'django/forms/p.html'``.
    
  665. 
    
  666. .. method:: Form.as_p()
    
  667. 
    
  668. ``as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>``
    
  669. containing one field::
    
  670. 
    
  671.     >>> f = ContactForm()
    
  672.     >>> f.as_p()
    
  673.     '<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></p>\n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></p>\n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" required></p>\n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></p>'
    
  674.     >>> print(f.as_p())
    
  675.     <p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></p>
    
  676.     <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></p>
    
  677.     <p><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></p>
    
  678.     <p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></p>
    
  679. 
    
  680. ``as_ul()``
    
  681. ~~~~~~~~~~~
    
  682. 
    
  683. .. attribute:: Form.template_name_ul
    
  684. 
    
  685. The template used by ``as_ul()``. Default: ``'django/forms/ul.html'``.
    
  686. 
    
  687. .. method:: Form.as_ul()
    
  688. 
    
  689. ``as_ul()`` renders the form as a series of ``<li>`` tags, with each ``<li>``
    
  690. containing one field. It does *not* include the ``<ul>`` or ``</ul>``, so that
    
  691. you can specify any HTML attributes on the ``<ul>`` for flexibility::
    
  692. 
    
  693.     >>> f = ContactForm()
    
  694.     >>> f.as_ul()
    
  695.     '<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></li>\n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></li>\n<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></li>\n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></li>'
    
  696.     >>> print(f.as_ul())
    
  697.     <li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></li>
    
  698.     <li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></li>
    
  699.     <li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></li>
    
  700.     <li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></li>
    
  701. 
    
  702. ``as_table()``
    
  703. ~~~~~~~~~~~~~~
    
  704. 
    
  705. .. attribute:: Form.template_name_table
    
  706. 
    
  707. The template used by ``as_table()``. Default: ``'django/forms/table.html'``.
    
  708. 
    
  709. .. method:: Form.as_table()
    
  710. 
    
  711. ``as_table()`` renders the form as an HTML ``<table>``::
    
  712. 
    
  713.     >>> f = ContactForm()
    
  714.     >>> f.as_table()
    
  715.     '<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr>\n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr>\n<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr>'
    
  716.     >>> print(f)
    
  717.     <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr>
    
  718.     <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr>
    
  719.     <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr>
    
  720.     <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr>
    
  721. 
    
  722. .. _ref-forms-api-styling-form-rows:
    
  723. 
    
  724. Styling required or erroneous form rows
    
  725. ---------------------------------------
    
  726. 
    
  727. .. attribute:: Form.error_css_class
    
  728. .. attribute:: Form.required_css_class
    
  729. 
    
  730. It's pretty common to style form rows and fields that are required or have
    
  731. errors. For example, you might want to present required form rows in bold and
    
  732. highlight errors in red.
    
  733. 
    
  734. The :class:`Form` class has a couple of hooks you can use to add ``class``
    
  735. attributes to required rows or to rows with errors: set the
    
  736. :attr:`Form.error_css_class` and/or :attr:`Form.required_css_class`
    
  737. attributes::
    
  738. 
    
  739.     from django import forms
    
  740. 
    
  741.     class ContactForm(forms.Form):
    
  742.         error_css_class = 'error'
    
  743.         required_css_class = 'required'
    
  744. 
    
  745.         # ... and the rest of your fields here
    
  746. 
    
  747. Once you've done that, rows will be given ``"error"`` and/or ``"required"``
    
  748. classes, as needed. The HTML will look something like::
    
  749. 
    
  750.     >>> f = ContactForm(data)
    
  751.     >>> print(f.as_table())
    
  752.     <tr class="required"><th><label class="required" for="id_subject">Subject:</label>    ...
    
  753.     <tr class="required"><th><label class="required" for="id_message">Message:</label>    ...
    
  754.     <tr class="required error"><th><label class="required" for="id_sender">Sender:</label>      ...
    
  755.     <tr><th><label for="id_cc_myself">Cc myself:<label> ...
    
  756.     >>> f['subject'].label_tag()
    
  757.     <label class="required" for="id_subject">Subject:</label>
    
  758.     >>> f['subject'].legend_tag()
    
  759.     <legend class="required" for="id_subject">Subject:</legend>
    
  760.     >>> f['subject'].label_tag(attrs={'class': 'foo'})
    
  761.     <label for="id_subject" class="foo required">Subject:</label>
    
  762.     >>> f['subject'].legend_tag(attrs={'class': 'foo'})
    
  763.     <legend for="id_subject" class="foo required">Subject:</legend>
    
  764. 
    
  765. .. _ref-forms-api-configuring-label:
    
  766. 
    
  767. Configuring form elements' HTML ``id`` attributes and ``<label>`` tags
    
  768. ----------------------------------------------------------------------
    
  769. 
    
  770. .. attribute:: Form.auto_id
    
  771. 
    
  772. By default, the form rendering methods include:
    
  773. 
    
  774. * HTML ``id`` attributes on the form elements.
    
  775. 
    
  776. * The corresponding ``<label>`` tags around the labels. An HTML ``<label>`` tag
    
  777.   designates which label text is associated with which form element. This small
    
  778.   enhancement makes forms more usable and more accessible to assistive devices.
    
  779.   It's always a good idea to use ``<label>`` tags.
    
  780. 
    
  781. The ``id`` attribute values are generated by prepending ``id_`` to the form
    
  782. field names.  This behavior is configurable, though, if you want to change the
    
  783. ``id`` convention or remove HTML ``id`` attributes and ``<label>`` tags
    
  784. entirely.
    
  785. 
    
  786. Use the ``auto_id`` argument to the ``Form`` constructor to control the ``id``
    
  787. and label behavior. This argument must be ``True``, ``False`` or a string.
    
  788. 
    
  789. If ``auto_id`` is ``False``, then the form output will not include ``<label>``
    
  790. tags nor ``id`` attributes::
    
  791. 
    
  792.     >>> f = ContactForm(auto_id=False)
    
  793.     >>> print(f.as_div())
    
  794.     <div>Subject:<input type="text" name="subject" maxlength="100" required></div>
    
  795.     <div>Message:<textarea name="message" cols="40" rows="10" required></textarea></div>
    
  796.     <div>Sender:<input type="email" name="sender" required></div>
    
  797.     <div>Cc myself:<input type="checkbox" name="cc_myself"></div>
    
  798. 
    
  799. If ``auto_id`` is set to ``True``, then the form output *will* include
    
  800. ``<label>`` tags and will use the field name as its ``id`` for each form
    
  801. field::
    
  802. 
    
  803.     >>> f = ContactForm(auto_id=True)
    
  804.     >>> print(f.as_div())
    
  805.     <div><label for="subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="subject"></div>
    
  806.     <div><label for="message">Message:</label><textarea name="message" cols="40" rows="10" required id="message"></textarea></div>
    
  807.     <div><label for="sender">Sender:</label><input type="email" name="sender" required id="sender"></div>
    
  808.     <div><label for="cc_myself">Cc myself:</label><input type="checkbox" name="cc_myself" id="cc_myself"></div>
    
  809. 
    
  810. If ``auto_id`` is set to a string containing the format character ``'%s'``,
    
  811. then the form output will include ``<label>`` tags, and will generate ``id``
    
  812. attributes based on the format string. For example, for a format string
    
  813. ``'field_%s'``, a field named ``subject`` will get the ``id`` value
    
  814. ``'field_subject'``. Continuing our example::
    
  815. 
    
  816.     >>> f = ContactForm(auto_id='id_for_%s')
    
  817.     >>> print(f.as_div())
    
  818.     <div><label for="id_for_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_for_subject"></div>
    
  819.     <div><label for="id_for_message">Message:</label><textarea name="message" cols="40" rows="10" required id="id_for_message"></textarea></div>
    
  820.     <div><label for="id_for_sender">Sender:</label><input type="email" name="sender" required id="id_for_sender"></div>
    
  821.     <div><label for="id_for_cc_myself">Cc myself:</label><input type="checkbox" name="cc_myself" id="id_for_cc_myself"></div>
    
  822. 
    
  823. If ``auto_id`` is set to any other true value -- such as a string that doesn't
    
  824. include ``%s`` -- then the library will act as if ``auto_id`` is ``True``.
    
  825. 
    
  826. By default, ``auto_id`` is set to the string ``'id_%s'``.
    
  827. 
    
  828. .. attribute:: Form.label_suffix
    
  829. 
    
  830. A translatable string (defaults to a colon (``:``) in English) that will be
    
  831. appended after any label name when a form is rendered.
    
  832. 
    
  833. It's possible to customize that character, or omit it entirely, using the
    
  834. ``label_suffix`` parameter::
    
  835. 
    
  836.     >>> f = ContactForm(auto_id='id_for_%s', label_suffix='')
    
  837.     >>> print(f.as_div())
    
  838.     <div><label for="id_for_subject">Subject</label><input type="text" name="subject" maxlength="100" required id="id_for_subject"></div>
    
  839.     <div><label for="id_for_message">Message</label><textarea name="message" cols="40" rows="10" required id="id_for_message"></textarea></div>
    
  840.     <div><label for="id_for_sender">Sender</label><input type="email" name="sender" required id="id_for_sender"></div>
    
  841.     <div><label for="id_for_cc_myself">Cc myself</label><input type="checkbox" name="cc_myself" id="id_for_cc_myself"></div>
    
  842.     >>> f = ContactForm(auto_id='id_for_%s', label_suffix=' ->')
    
  843.     >>> print(f.as_div())
    
  844.     <div><label for="id_for_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_for_subject"></div>
    
  845.     <div><label for="id_for_message">Message -&gt;</label><textarea name="message" cols="40" rows="10" required id="id_for_message"></textarea></div>
    
  846.     <div><label for="id_for_sender">Sender -&gt;</label><input type="email" name="sender" required id="id_for_sender"></div>
    
  847.     <div><label for="id_for_cc_myself">Cc myself -&gt;</label><input type="checkbox" name="cc_myself" id="id_for_cc_myself"></div>
    
  848. 
    
  849. Note that the label suffix is added only if the last character of the
    
  850. label isn't a punctuation character (in English, those are ``.``, ``!``, ``?``
    
  851. or ``:``).
    
  852. 
    
  853. Fields can also define their own :attr:`~django.forms.Field.label_suffix`.
    
  854. This will take precedence over :attr:`Form.label_suffix
    
  855. <django.forms.Form.label_suffix>`. The suffix can also be overridden at runtime
    
  856. using the ``label_suffix`` parameter to
    
  857. :meth:`~django.forms.BoundField.label_tag`/
    
  858. :meth:`~django.forms.BoundField.legend_tag`.
    
  859. 
    
  860. .. attribute:: Form.use_required_attribute
    
  861. 
    
  862. When set to ``True`` (the default), required form fields will have the
    
  863. ``required`` HTML attribute.
    
  864. 
    
  865. :doc:`Formsets </topics/forms/formsets>` instantiate forms with
    
  866. ``use_required_attribute=False`` to avoid incorrect browser validation when
    
  867. adding and deleting forms from a formset.
    
  868. 
    
  869. Configuring the rendering of a form's widgets
    
  870. ---------------------------------------------
    
  871. 
    
  872. .. attribute:: Form.default_renderer
    
  873. 
    
  874. Specifies the :doc:`renderer <renderers>` to use for the form. Defaults to
    
  875. ``None`` which means to use the default renderer specified by the
    
  876. :setting:`FORM_RENDERER` setting.
    
  877. 
    
  878. You can set this as a class attribute when declaring your form or use the
    
  879. ``renderer`` argument to ``Form.__init__()``. For example::
    
  880. 
    
  881.     from django import forms
    
  882. 
    
  883.     class MyForm(forms.Form):
    
  884.         default_renderer = MyRenderer()
    
  885. 
    
  886. or::
    
  887. 
    
  888.     form = MyForm(renderer=MyRenderer())
    
  889. 
    
  890. Notes on field ordering
    
  891. -----------------------
    
  892. 
    
  893. In the ``as_p()``, ``as_ul()`` and ``as_table()`` shortcuts, the fields are
    
  894. displayed in the order in which you define them in your form class. For
    
  895. example, in the ``ContactForm`` example, the fields are defined in the order
    
  896. ``subject``, ``message``, ``sender``, ``cc_myself``. To reorder the HTML
    
  897. output, change the order in which those fields are listed in the class.
    
  898. 
    
  899. There are several other ways to customize the order:
    
  900. 
    
  901. .. attribute:: Form.field_order
    
  902. 
    
  903. By default ``Form.field_order=None``, which retains the order in which you
    
  904. define the fields in your form class. If ``field_order`` is a list of field
    
  905. names, the fields are ordered as specified by the list and remaining fields are
    
  906. appended according to the default order. Unknown field names in the list are
    
  907. ignored. This makes it possible to disable a field in a subclass by setting it
    
  908. to ``None`` without having to redefine ordering.
    
  909. 
    
  910. You can also use the ``Form.field_order`` argument to a :class:`Form` to
    
  911. override the field order. If a :class:`~django.forms.Form` defines
    
  912. :attr:`~Form.field_order` *and* you include ``field_order`` when instantiating
    
  913. the ``Form``, then the latter ``field_order`` will have precedence.
    
  914. 
    
  915. .. method:: Form.order_fields(field_order)
    
  916. 
    
  917. You may rearrange the fields any time using ``order_fields()`` with a list of
    
  918. field names as in :attr:`~django.forms.Form.field_order`.
    
  919. 
    
  920. How errors are displayed
    
  921. ------------------------
    
  922. 
    
  923. If you render a bound ``Form`` object, the act of rendering will automatically
    
  924. run the form's validation if it hasn't already happened, and the HTML output
    
  925. will include the validation errors as a ``<ul class="errorlist">`` near the
    
  926. field. The particular positioning of the error messages depends on the output
    
  927. method you're using::
    
  928. 
    
  929.     >>> data = {'subject': '',
    
  930.     ...         'message': 'Hi there',
    
  931.     ...         'sender': 'invalid email address',
    
  932.     ...         'cc_myself': True}
    
  933.     >>> f = ContactForm(data, auto_id=False)
    
  934.     >>> print(f.as_div())
    
  935.     <div>Subject:<ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" required></div>
    
  936.     <div>Message:<textarea name="message" cols="40" rows="10" required>Hi there</textarea></div>
    
  937.     <div>Sender:<ul class="errorlist"><li>Enter a valid email address.</li></ul><input type="email" name="sender" value="invalid email address" required></div>
    
  938.     <div>Cc myself:<input type="checkbox" name="cc_myself" checked></div>
    
  939.     >>> print(f.as_table())
    
  940.     <tr><th>Subject:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" required></td></tr>
    
  941.     <tr><th>Message:</th><td><textarea name="message" cols="40" rows="10" required></textarea></td></tr>
    
  942.     <tr><th>Sender:</th><td><ul class="errorlist"><li>Enter a valid email address.</li></ul><input type="email" name="sender" value="invalid email address" required></td></tr>
    
  943.     <tr><th>Cc myself:</th><td><input checked type="checkbox" name="cc_myself"></td></tr>
    
  944.     >>> print(f.as_ul())
    
  945.     <li><ul class="errorlist"><li>This field is required.</li></ul>Subject: <input type="text" name="subject" maxlength="100" required></li>
    
  946.     <li>Message: <textarea name="message" cols="40" rows="10" required></textarea></li>
    
  947.     <li><ul class="errorlist"><li>Enter a valid email address.</li></ul>Sender: <input type="email" name="sender" value="invalid email address" required></li>
    
  948.     <li>Cc myself: <input checked type="checkbox" name="cc_myself"></li>
    
  949.     >>> print(f.as_p())
    
  950.     <p><ul class="errorlist"><li>This field is required.</li></ul></p>
    
  951.     <p>Subject: <input type="text" name="subject" maxlength="100" required></p>
    
  952.     <p>Message: <textarea name="message" cols="40" rows="10" required></textarea></p>
    
  953.     <p><ul class="errorlist"><li>Enter a valid email address.</li></ul></p>
    
  954.     <p>Sender: <input type="email" name="sender" value="invalid email address" required></p>
    
  955.     <p>Cc myself: <input checked type="checkbox" name="cc_myself"></p>
    
  956. 
    
  957. .. _ref-forms-error-list-format:
    
  958. 
    
  959. Customizing the error list format
    
  960. ---------------------------------
    
  961. 
    
  962. .. class:: ErrorList(initlist=None, error_class=None, renderer=None)
    
  963. 
    
  964.     By default, forms use ``django.forms.utils.ErrorList`` to format validation
    
  965.     errors. ``ErrorList`` is a list like object where ``initlist`` is the
    
  966.     list of errors. In addition this class has the following attributes and
    
  967.     methods.
    
  968. 
    
  969.     .. attribute:: error_class
    
  970. 
    
  971.         The CSS classes to be used when rendering the error list. Any provided
    
  972.         classes are added to the default ``errorlist`` class.
    
  973. 
    
  974.     .. attribute:: renderer
    
  975. 
    
  976.         .. versionadded:: 4.0
    
  977. 
    
  978.         Specifies the :doc:`renderer <renderers>` to use for ``ErrorList``.
    
  979.         Defaults to ``None`` which means to use the default renderer
    
  980.         specified by the :setting:`FORM_RENDERER` setting.
    
  981. 
    
  982.     .. attribute:: template_name
    
  983. 
    
  984.         .. versionadded:: 4.0
    
  985. 
    
  986.         The name of the template used when calling ``__str__`` or
    
  987.         :meth:`render`. By default this is
    
  988.         ``'django/forms/errors/list/default.html'`` which is a proxy for the
    
  989.         ``'ul.html'`` template.
    
  990. 
    
  991.     .. attribute:: template_name_text
    
  992. 
    
  993.         .. versionadded:: 4.0
    
  994. 
    
  995.         The name of the template used when calling :meth:`.as_text`. By default
    
  996.         this is ``'django/forms/errors/list/text.html'``. This template renders
    
  997.         the errors as a list of bullet points.
    
  998. 
    
  999.     .. attribute:: template_name_ul
    
  1000. 
    
  1001.         .. versionadded:: 4.0
    
  1002. 
    
  1003.         The name of the template used when calling :meth:`.as_ul`. By default
    
  1004.         this is ``'django/forms/errors/list/ul.html'``. This template renders
    
  1005.         the errors in ``<li>`` tags with a wrapping ``<ul>`` with the CSS
    
  1006.         classes as defined by :attr:`.error_class`.
    
  1007. 
    
  1008.     .. method:: get_context()
    
  1009. 
    
  1010.         .. versionadded:: 4.0
    
  1011. 
    
  1012.         Return context for rendering of errors in a template.
    
  1013. 
    
  1014.         The available context is:
    
  1015. 
    
  1016.         * ``errors`` : A list of the errors.
    
  1017.         * ``error_class`` : A string of CSS classes.
    
  1018. 
    
  1019.     .. method:: render(template_name=None, context=None, renderer=None)
    
  1020. 
    
  1021.         .. versionadded:: 4.0
    
  1022. 
    
  1023.         The render method is called by ``__str__`` as well as by the
    
  1024.         :meth:`.as_ul` method.
    
  1025. 
    
  1026.         All arguments are optional and will default to:
    
  1027. 
    
  1028.         * ``template_name``: Value returned by :attr:`.template_name`
    
  1029.         * ``context``: Value returned by :meth:`.get_context`
    
  1030.         * ``renderer``: Value returned by :attr:`.renderer`
    
  1031. 
    
  1032.     .. method:: as_text()
    
  1033. 
    
  1034.         Renders the error list using the template defined by
    
  1035.         :attr:`.template_name_text`.
    
  1036. 
    
  1037.     .. method:: as_ul()
    
  1038. 
    
  1039.         Renders the error list using the template defined by
    
  1040.         :attr:`.template_name_ul`.
    
  1041. 
    
  1042.     If you'd like to customize the rendering of errors this can be achieved by
    
  1043.     overriding the :attr:`.template_name` attribute or more generally by
    
  1044.     overriding the default template, see also
    
  1045.     :ref:`overriding-built-in-form-templates`.
    
  1046. 
    
  1047. .. versionchanged:: 4.0
    
  1048. 
    
  1049.     Rendering of :class:`ErrorList` was moved to the template engine.
    
  1050. 
    
  1051. .. deprecated:: 4.0
    
  1052. 
    
  1053.     The ability to return a ``str`` when calling the ``__str__`` method is
    
  1054.     deprecated. Use the template engine instead which returns a ``SafeString``.
    
  1055. 
    
  1056. More granular output
    
  1057. ====================
    
  1058. 
    
  1059. The ``as_p()``, ``as_ul()``, and ``as_table()`` methods are shortcuts --
    
  1060. they're not the only way a form object can be displayed.
    
  1061. 
    
  1062. .. class:: BoundField
    
  1063. 
    
  1064.    Used to display HTML or access attributes for a single field of a
    
  1065.    :class:`Form` instance.
    
  1066. 
    
  1067.    The ``__str__()`` method of this object displays the HTML for this field.
    
  1068. 
    
  1069. To retrieve a single ``BoundField``, use dictionary lookup syntax on your form
    
  1070. using the field's name as the key::
    
  1071. 
    
  1072.     >>> form = ContactForm()
    
  1073.     >>> print(form['subject'])
    
  1074.     <input id="id_subject" type="text" name="subject" maxlength="100" required>
    
  1075. 
    
  1076. To retrieve all ``BoundField`` objects, iterate the form::
    
  1077. 
    
  1078.     >>> form = ContactForm()
    
  1079.     >>> for boundfield in form: print(boundfield)
    
  1080.     <input id="id_subject" type="text" name="subject" maxlength="100" required>
    
  1081.     <input type="text" name="message" id="id_message" required>
    
  1082.     <input type="email" name="sender" id="id_sender" required>
    
  1083.     <input type="checkbox" name="cc_myself" id="id_cc_myself">
    
  1084. 
    
  1085. The field-specific output honors the form object's ``auto_id`` setting::
    
  1086. 
    
  1087.     >>> f = ContactForm(auto_id=False)
    
  1088.     >>> print(f['message'])
    
  1089.     <input type="text" name="message" required>
    
  1090.     >>> f = ContactForm(auto_id='id_%s')
    
  1091.     >>> print(f['message'])
    
  1092.     <input type="text" name="message" id="id_message" required>
    
  1093. 
    
  1094. Attributes of ``BoundField``
    
  1095. ----------------------------
    
  1096. 
    
  1097. .. attribute:: BoundField.auto_id
    
  1098. 
    
  1099.     The HTML ID attribute for this ``BoundField``. Returns an empty string
    
  1100.     if :attr:`Form.auto_id` is ``False``.
    
  1101. 
    
  1102. .. attribute:: BoundField.data
    
  1103. 
    
  1104.     This property returns the data for this :class:`~django.forms.BoundField`
    
  1105.     extracted by the widget's :meth:`~django.forms.Widget.value_from_datadict`
    
  1106.     method, or ``None`` if it wasn't given::
    
  1107. 
    
  1108.         >>> unbound_form = ContactForm()
    
  1109.         >>> print(unbound_form['subject'].data)
    
  1110.         None
    
  1111.         >>> bound_form = ContactForm(data={'subject': 'My Subject'})
    
  1112.         >>> print(bound_form['subject'].data)
    
  1113.         My Subject
    
  1114. 
    
  1115. .. attribute:: BoundField.errors
    
  1116. 
    
  1117.     A :ref:`list-like object <ref-forms-error-list-format>` that is displayed
    
  1118.     as an HTML ``<ul class="errorlist">`` when printed::
    
  1119. 
    
  1120.         >>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''}
    
  1121.         >>> f = ContactForm(data, auto_id=False)
    
  1122.         >>> print(f['message'])
    
  1123.         <input type="text" name="message" required>
    
  1124.         >>> f['message'].errors
    
  1125.         ['This field is required.']
    
  1126.         >>> print(f['message'].errors)
    
  1127.         <ul class="errorlist"><li>This field is required.</li></ul>
    
  1128.         >>> f['subject'].errors
    
  1129.         []
    
  1130.         >>> print(f['subject'].errors)
    
  1131. 
    
  1132.         >>> str(f['subject'].errors)
    
  1133.         ''
    
  1134. 
    
  1135. .. attribute:: BoundField.field
    
  1136. 
    
  1137.     The form :class:`~django.forms.Field` instance from the form class that
    
  1138.     this :class:`~django.forms.BoundField` wraps.
    
  1139. 
    
  1140. .. attribute:: BoundField.form
    
  1141. 
    
  1142.     The :class:`~django.forms.Form` instance this :class:`~django.forms.BoundField`
    
  1143.     is bound to.
    
  1144. 
    
  1145. .. attribute:: BoundField.help_text
    
  1146. 
    
  1147.     The :attr:`~django.forms.Field.help_text` of the field.
    
  1148. 
    
  1149. .. attribute:: BoundField.html_name
    
  1150. 
    
  1151.     The name that will be used in the widget's HTML ``name`` attribute. It takes
    
  1152.     the form :attr:`~django.forms.Form.prefix` into account.
    
  1153. 
    
  1154. .. attribute:: BoundField.id_for_label
    
  1155. 
    
  1156.     Use this property to render the ID of this field. For example, if you are
    
  1157.     manually constructing a ``<label>`` in your template (despite the fact that
    
  1158.     :meth:`~BoundField.label_tag`/:meth:`~BoundField.legend_tag` will do this
    
  1159.     for you):
    
  1160. 
    
  1161.     .. code-block:: html+django
    
  1162. 
    
  1163.         <label for="{{ form.my_field.id_for_label }}">...</label>{{ my_field }}
    
  1164. 
    
  1165.     By default, this will be the field's name prefixed by ``id_``
    
  1166.     ("``id_my_field``" for the example above). You may modify the ID by setting
    
  1167.     :attr:`~django.forms.Widget.attrs` on the field's widget. For example,
    
  1168.     declaring a field like this::
    
  1169. 
    
  1170.         my_field = forms.CharField(widget=forms.TextInput(attrs={'id': 'myFIELD'}))
    
  1171. 
    
  1172.     and using the template above, would render something like:
    
  1173. 
    
  1174.     .. code-block:: html
    
  1175. 
    
  1176.         <label for="myFIELD">...</label><input id="myFIELD" type="text" name="my_field" required>
    
  1177. 
    
  1178. .. attribute:: BoundField.initial
    
  1179. 
    
  1180.     Use :attr:`BoundField.initial` to retrieve initial data for a form field.
    
  1181.     It retrieves the data from :attr:`Form.initial` if present, otherwise
    
  1182.     trying :attr:`Field.initial`. Callable values are evaluated. See
    
  1183.     :ref:`ref-forms-initial-form-values` for more examples.
    
  1184. 
    
  1185.     :attr:`BoundField.initial` caches its return value, which is useful
    
  1186.     especially when dealing with callables whose return values can change (e.g.
    
  1187.     ``datetime.now`` or ``uuid.uuid4``)::
    
  1188. 
    
  1189.         >>> from datetime import datetime
    
  1190.         >>> class DatedCommentForm(CommentForm):
    
  1191.         ...     created = forms.DateTimeField(initial=datetime.now)
    
  1192.         >>> f = DatedCommentForm()
    
  1193.         >>> f['created'].initial
    
  1194.         datetime.datetime(2021, 7, 27, 9, 5, 54)
    
  1195.         >>> f['created'].initial
    
  1196.         datetime.datetime(2021, 7, 27, 9, 5, 54)
    
  1197. 
    
  1198.     Using :attr:`BoundField.initial` is recommended over
    
  1199.     :meth:`~Form.get_initial_for_field()`.
    
  1200. 
    
  1201. .. attribute:: BoundField.is_hidden
    
  1202. 
    
  1203.     Returns ``True`` if this :class:`~django.forms.BoundField`'s widget is
    
  1204.     hidden.
    
  1205. 
    
  1206. .. attribute:: BoundField.label
    
  1207. 
    
  1208.     The :attr:`~django.forms.Field.label` of the field. This is used in
    
  1209.     :meth:`~BoundField.label_tag`/:meth:`~BoundField.legend_tag`.
    
  1210. 
    
  1211. .. attribute:: BoundField.name
    
  1212. 
    
  1213.     The name of this field in the form::
    
  1214. 
    
  1215.         >>> f = ContactForm()
    
  1216.         >>> print(f['subject'].name)
    
  1217.         subject
    
  1218.         >>> print(f['message'].name)
    
  1219.         message
    
  1220. 
    
  1221. .. attribute:: BoundField.use_fieldset
    
  1222. 
    
  1223.     .. versionadded:: 4.1
    
  1224. 
    
  1225.     Returns the value of this BoundField widget's ``use_fieldset`` attribute.
    
  1226. 
    
  1227. .. attribute:: BoundField.widget_type
    
  1228. 
    
  1229.     Returns the lowercased class name of the wrapped field's widget, with any
    
  1230.     trailing ``input`` or ``widget`` removed. This may be used when building
    
  1231.     forms where the layout is dependent upon the widget type. For example::
    
  1232. 
    
  1233.         {% for field in form %}
    
  1234.             {% if field.widget_type == 'checkbox' %}
    
  1235.                 # render one way
    
  1236.             {% else %}
    
  1237.                 # render another way
    
  1238.             {% endif %}
    
  1239.         {% endfor %}
    
  1240. 
    
  1241. 
    
  1242. Methods of ``BoundField``
    
  1243. -------------------------
    
  1244. 
    
  1245. .. method:: BoundField.as_hidden(attrs=None, **kwargs)
    
  1246. 
    
  1247.     Returns a string of HTML for representing this as an ``<input type="hidden">``.
    
  1248. 
    
  1249.     ``**kwargs`` are passed to :meth:`~django.forms.BoundField.as_widget`.
    
  1250. 
    
  1251.     This method is primarily used internally. You should use a widget instead.
    
  1252. 
    
  1253. .. method:: BoundField.as_widget(widget=None, attrs=None, only_initial=False)
    
  1254. 
    
  1255.     Renders the field by rendering the passed widget, adding any HTML
    
  1256.     attributes passed as ``attrs``.  If no widget is specified, then the
    
  1257.     field's default widget will be used.
    
  1258. 
    
  1259.     ``only_initial`` is used by Django internals and should not be set
    
  1260.     explicitly.
    
  1261. 
    
  1262. .. method:: BoundField.css_classes(extra_classes=None)
    
  1263. 
    
  1264.     When you use Django's rendering shortcuts, CSS classes are used to
    
  1265.     indicate required form fields or fields that contain errors. If you're
    
  1266.     manually rendering a form, you can access these CSS classes using the
    
  1267.     ``css_classes`` method::
    
  1268. 
    
  1269.         >>> f = ContactForm(data={'message': ''})
    
  1270.         >>> f['message'].css_classes()
    
  1271.         'required'
    
  1272. 
    
  1273.     If you want to provide some additional classes in addition to the
    
  1274.     error and required classes that may be required, you can provide
    
  1275.     those classes as an argument::
    
  1276. 
    
  1277.         >>> f = ContactForm(data={'message': ''})
    
  1278.         >>> f['message'].css_classes('foo bar')
    
  1279.         'foo bar required'
    
  1280. 
    
  1281. .. method:: BoundField.label_tag(contents=None, attrs=None, label_suffix=None, tag=None)
    
  1282. 
    
  1283.     Renders a label tag for the form field using the template specified by
    
  1284.     :attr:`.Form.template_name_label`.
    
  1285. 
    
  1286.     The available context is:
    
  1287. 
    
  1288.     * ``field``: This instance of the :class:`BoundField`.
    
  1289.     * ``contents``: By default a concatenated string of
    
  1290.       :attr:`BoundField.label` and :attr:`Form.label_suffix` (or
    
  1291.       :attr:`Field.label_suffix`, if set). This can be overridden by the
    
  1292.       ``contents`` and ``label_suffix`` arguments.
    
  1293.     * ``attrs``: A ``dict`` containing ``for``,
    
  1294.       :attr:`Form.required_css_class`, and ``id``. ``id`` is generated by the
    
  1295.       field's widget ``attrs`` or :attr:`BoundField.auto_id`. Additional
    
  1296.       attributes can be provided by the ``attrs`` argument.
    
  1297.     * ``use_tag``: A boolean which is ``True`` if the label has an ``id``.
    
  1298.       If ``False`` the default template omits the ``tag``.
    
  1299.     * ``tag``: An optional string to customize the tag, defaults to ``label``.
    
  1300. 
    
  1301.     .. tip::
    
  1302. 
    
  1303.         In your template ``field`` is the instance of the ``BoundField``.
    
  1304.         Therefore ``field.field`` accesses :attr:`BoundField.field` being
    
  1305.         the field you declare, e.g. ``forms.CharField``.
    
  1306. 
    
  1307.     To separately render the label tag of a form field, you can call its
    
  1308.     ``label_tag()`` method::
    
  1309. 
    
  1310.         >>> f = ContactForm(data={'message': ''})
    
  1311.         >>> print(f['message'].label_tag())
    
  1312.         <label for="id_message">Message:</label>
    
  1313. 
    
  1314.     If you'd like to customize the rendering this can be achieved by overriding
    
  1315.     the :attr:`.Form.template_name_label` attribute or more generally by
    
  1316.     overriding the default template, see also
    
  1317.     :ref:`overriding-built-in-form-templates`.
    
  1318. 
    
  1319.     .. versionchanged:: 4.0
    
  1320. 
    
  1321.         The label is now rendered using the template engine.
    
  1322. 
    
  1323.     .. versionchanged:: 4.1
    
  1324. 
    
  1325.         The ``tag`` argument was added.
    
  1326. 
    
  1327. .. method:: BoundField.legend_tag(contents=None, attrs=None, label_suffix=None)
    
  1328. 
    
  1329.     .. versionadded:: 4.1
    
  1330. 
    
  1331.     Calls :meth:`.label_tag` with ``tag='legend'`` to render the label with
    
  1332.     ``<legend>`` tags. This is useful when rendering radio and multiple
    
  1333.     checkbox widgets where ``<legend>`` may be more appropriate than a
    
  1334.     ``<label>``.
    
  1335. 
    
  1336. .. method:: BoundField.value()
    
  1337. 
    
  1338.     Use this method to render the raw value of this field as it would be rendered
    
  1339.     by a ``Widget``::
    
  1340. 
    
  1341.         >>> initial = {'subject': 'welcome'}
    
  1342.         >>> unbound_form = ContactForm(initial=initial)
    
  1343.         >>> bound_form = ContactForm(data={'subject': 'hi'}, initial=initial)
    
  1344.         >>> print(unbound_form['subject'].value())
    
  1345.         welcome
    
  1346.         >>> print(bound_form['subject'].value())
    
  1347.         hi
    
  1348. 
    
  1349. Customizing ``BoundField``
    
  1350. ==========================
    
  1351. 
    
  1352. If you need to access some additional information about a form field in a
    
  1353. template and using a subclass of :class:`~django.forms.Field` isn't
    
  1354. sufficient, consider also customizing :class:`~django.forms.BoundField`.
    
  1355. 
    
  1356. A custom form field can override ``get_bound_field()``:
    
  1357. 
    
  1358. .. method:: Field.get_bound_field(form, field_name)
    
  1359. 
    
  1360.     Takes an instance of :class:`~django.forms.Form` and the name of the field.
    
  1361.     The return value will be used when accessing the field in a template. Most
    
  1362.     likely it will be an instance of a subclass of
    
  1363.     :class:`~django.forms.BoundField`.
    
  1364. 
    
  1365. If you have a ``GPSCoordinatesField``, for example, and want to be able to
    
  1366. access additional information about the coordinates in a template, this could
    
  1367. be implemented as follows::
    
  1368. 
    
  1369.     class GPSCoordinatesBoundField(BoundField):
    
  1370.         @property
    
  1371.         def country(self):
    
  1372.             """
    
  1373.             Return the country the coordinates lie in or None if it can't be
    
  1374.             determined.
    
  1375.             """
    
  1376.             value = self.value()
    
  1377.             if value:
    
  1378.                 return get_country_from_coordinates(value)
    
  1379.             else:
    
  1380.                 return None
    
  1381. 
    
  1382.     class GPSCoordinatesField(Field):
    
  1383.         def get_bound_field(self, form, field_name):
    
  1384.             return GPSCoordinatesBoundField(form, self, field_name)
    
  1385. 
    
  1386. Now you can access the country in a template with
    
  1387. ``{{ form.coordinates.country }}``.
    
  1388. 
    
  1389. .. _binding-uploaded-files:
    
  1390. 
    
  1391. Binding uploaded files to a form
    
  1392. ================================
    
  1393. 
    
  1394. Dealing with forms that have ``FileField`` and ``ImageField`` fields
    
  1395. is a little more complicated than a normal form.
    
  1396. 
    
  1397. Firstly, in order to upload files, you'll need to make sure that your
    
  1398. ``<form>`` element correctly defines the ``enctype`` as
    
  1399. ``"multipart/form-data"``::
    
  1400. 
    
  1401.   <form enctype="multipart/form-data" method="post" action="/foo/">
    
  1402. 
    
  1403. Secondly, when you use the form, you need to bind the file data. File
    
  1404. data is handled separately to normal form data, so when your form
    
  1405. contains a ``FileField`` and ``ImageField``, you will need to specify
    
  1406. a second argument when you bind your form. So if we extend our
    
  1407. ContactForm to include an ``ImageField`` called ``mugshot``, we
    
  1408. need to bind the file data containing the mugshot image::
    
  1409. 
    
  1410.     # Bound form with an image field
    
  1411.     >>> from django.core.files.uploadedfile import SimpleUploadedFile
    
  1412.     >>> data = {'subject': 'hello',
    
  1413.     ...         'message': 'Hi there',
    
  1414.     ...         'sender': '[email protected]',
    
  1415.     ...         'cc_myself': True}
    
  1416.     >>> file_data = {'mugshot': SimpleUploadedFile('face.jpg', <file data>)}
    
  1417.     >>> f = ContactFormWithMugshot(data, file_data)
    
  1418. 
    
  1419. In practice, you will usually specify ``request.FILES`` as the source
    
  1420. of file data (just like you use ``request.POST`` as the source of
    
  1421. form data)::
    
  1422. 
    
  1423.     # Bound form with an image field, data from the request
    
  1424.     >>> f = ContactFormWithMugshot(request.POST, request.FILES)
    
  1425. 
    
  1426. Constructing an unbound form is the same as always -- omit both form data *and*
    
  1427. file data::
    
  1428. 
    
  1429.     # Unbound form with an image field
    
  1430.     >>> f = ContactFormWithMugshot()
    
  1431. 
    
  1432. Testing for multipart forms
    
  1433. ---------------------------
    
  1434. 
    
  1435. .. method:: Form.is_multipart()
    
  1436. 
    
  1437. If you're writing reusable views or templates, you may not know ahead of time
    
  1438. whether your form is a multipart form or not. The ``is_multipart()`` method
    
  1439. tells you whether the form requires multipart encoding for submission::
    
  1440. 
    
  1441.     >>> f = ContactFormWithMugshot()
    
  1442.     >>> f.is_multipart()
    
  1443.     True
    
  1444. 
    
  1445. Here's an example of how you might use this in a template::
    
  1446. 
    
  1447.     {% if form.is_multipart %}
    
  1448.         <form enctype="multipart/form-data" method="post" action="/foo/">
    
  1449.     {% else %}
    
  1450.         <form method="post" action="/foo/">
    
  1451.     {% endif %}
    
  1452.     {{ form }}
    
  1453.     </form>
    
  1454. 
    
  1455. Subclassing forms
    
  1456. =================
    
  1457. 
    
  1458. If you have multiple ``Form`` classes that share fields, you can use
    
  1459. subclassing to remove redundancy.
    
  1460. 
    
  1461. When you subclass a custom ``Form`` class, the resulting subclass will
    
  1462. include all fields of the parent class(es), followed by the fields you define
    
  1463. in the subclass.
    
  1464. 
    
  1465. In this example, ``ContactFormWithPriority`` contains all the fields from
    
  1466. ``ContactForm``, plus an additional field, ``priority``. The ``ContactForm``
    
  1467. fields are ordered first::
    
  1468. 
    
  1469.     >>> class ContactFormWithPriority(ContactForm):
    
  1470.     ...     priority = forms.CharField()
    
  1471.     >>> f = ContactFormWithPriority(auto_id=False)
    
  1472.     >>> print(f.as_div())
    
  1473.     <div>Subject:<input type="text" name="subject" maxlength="100" required></div>
    
  1474.     <div>Message:<textarea name="message" cols="40" rows="10" required></textarea></div>
    
  1475.     <div>Sender:<input type="email" name="sender" required></div>
    
  1476.     <div>Cc myself:<input type="checkbox" name="cc_myself"></div>
    
  1477.     <div>Priority:<input type="text" name="priority" required></div>
    
  1478. 
    
  1479. It's possible to subclass multiple forms, treating forms as mixins. In this
    
  1480. example, ``BeatleForm`` subclasses both ``PersonForm`` and ``InstrumentForm``
    
  1481. (in that order), and its field list includes the fields from the parent
    
  1482. classes::
    
  1483. 
    
  1484.     >>> from django import forms
    
  1485.     >>> class PersonForm(forms.Form):
    
  1486.     ...     first_name = forms.CharField()
    
  1487.     ...     last_name = forms.CharField()
    
  1488.     >>> class InstrumentForm(forms.Form):
    
  1489.     ...     instrument = forms.CharField()
    
  1490.     >>> class BeatleForm(InstrumentForm, PersonForm):
    
  1491.     ...     haircut_type = forms.CharField()
    
  1492.     >>> b = BeatleForm(auto_id=False)
    
  1493.     >>> print(b.as_div())
    
  1494.     <div>First name:<input type="text" name="first_name" required></div>
    
  1495.     <div>Last name:<input type="text" name="last_name" required></div>
    
  1496.     <div>Instrument:<input type="text" name="instrument" required></div>
    
  1497.     <div>Haircut type:<input type="text" name="haircut_type" required></div>
    
  1498. 
    
  1499. It's possible to declaratively remove a ``Field`` inherited from a parent class
    
  1500. by setting the name of the field to ``None`` on the subclass. For example::
    
  1501. 
    
  1502.     >>> from django import forms
    
  1503. 
    
  1504.     >>> class ParentForm(forms.Form):
    
  1505.     ...     name = forms.CharField()
    
  1506.     ...     age = forms.IntegerField()
    
  1507. 
    
  1508.     >>> class ChildForm(ParentForm):
    
  1509.     ...     name = None
    
  1510. 
    
  1511.     >>> list(ChildForm().fields)
    
  1512.     ['age']
    
  1513. 
    
  1514. .. _form-prefix:
    
  1515. 
    
  1516. Prefixes for forms
    
  1517. ==================
    
  1518. 
    
  1519. .. attribute:: Form.prefix
    
  1520. 
    
  1521. You can put several Django forms inside one ``<form>`` tag. To give each
    
  1522. ``Form`` its own namespace, use the ``prefix`` keyword argument::
    
  1523. 
    
  1524.     >>> mother = PersonForm(prefix="mother")
    
  1525.     >>> father = PersonForm(prefix="father")
    
  1526.     >>> print(mother.as_div())
    
  1527.     <div><label for="id_mother-first_name">First name:</label><input type="text" name="mother-first_name" required id="id_mother-first_name"></div>
    
  1528.     <div><label for="id_mother-last_name">Last name:</label><input type="text" name="mother-last_name" required id="id_mother-last_name"></div>
    
  1529.     >>> print(father.as_div())
    
  1530.     <div><label for="id_father-first_name">First name:</label><input type="text" name="father-first_name" required id="id_father-first_name"></div>
    
  1531.     <div><label for="id_father-last_name">Last name:</label><input type="text" name="father-last_name" required id="id_father-last_name"></div>
    
  1532. 
    
  1533. The prefix can also be specified on the form class::
    
  1534. 
    
  1535.     >>> class PersonForm(forms.Form):
    
  1536.     ...     ...
    
  1537.     ...     prefix = 'person'