1. ==================
    
  2. Working with forms
    
  3. ==================
    
  4. 
    
  5. .. currentmodule:: django.forms
    
  6. 
    
  7. .. admonition:: About this document
    
  8. 
    
  9.     This document provides an introduction to the basics of web forms and how
    
  10.     they are handled in Django. For a more detailed look at specific areas of
    
  11.     the forms API, see :doc:`/ref/forms/api`, :doc:`/ref/forms/fields`, and
    
  12.     :doc:`/ref/forms/validation`.
    
  13. 
    
  14. Unless you're planning to build websites and applications that do nothing but
    
  15. publish content, and don't accept input from your visitors, you're going to
    
  16. need to understand and use forms.
    
  17. 
    
  18. Django provides a range of tools and libraries to help you build forms to
    
  19. accept input from site visitors, and then process and respond to the input.
    
  20. 
    
  21. HTML forms
    
  22. ==========
    
  23. 
    
  24. In HTML, a form is a collection of elements inside ``<form>...</form>`` that
    
  25. allow a visitor to do things like enter text, select options, manipulate
    
  26. objects or controls, and so on, and then send that information back to the
    
  27. server.
    
  28. 
    
  29. Some of these form interface elements - text input or checkboxes - are built
    
  30. into HTML itself. Others are much more complex; an interface that pops up a
    
  31. date picker or allows you to move a slider or manipulate controls will
    
  32. typically use JavaScript and CSS as well as HTML form ``<input>`` elements to
    
  33. achieve these effects.
    
  34. 
    
  35. As well as its ``<input>`` elements, a form must specify two things:
    
  36. 
    
  37. * *where*: the URL to which the data corresponding to the user's input should
    
  38.   be returned
    
  39. 
    
  40. * *how*: the HTTP method the data should be returned by
    
  41. 
    
  42. As an example, the login form for the Django admin contains several
    
  43. ``<input>`` elements: one of ``type="text"`` for the username, one of
    
  44. ``type="password"`` for the password, and one of ``type="submit"`` for the
    
  45. "Log in" button. It also contains some hidden text fields that the user
    
  46. doesn't see, which Django uses to determine what to do next.
    
  47. 
    
  48. It also tells the browser that the form data should be sent to the URL
    
  49. specified in the ``<form>``’s ``action`` attribute - ``/admin/`` - and that it
    
  50. should be sent using the HTTP mechanism specified by the ``method`` attribute -
    
  51. ``post``.
    
  52. 
    
  53. When the ``<input type="submit" value="Log in">`` element is triggered, the
    
  54. data is returned to ``/admin/``.
    
  55. 
    
  56. ``GET`` and ``POST``
    
  57. --------------------
    
  58. 
    
  59. ``GET`` and ``POST`` are the only HTTP methods to use when dealing with forms.
    
  60. 
    
  61. Django's login form is returned using the ``POST`` method, in which the browser
    
  62. bundles up the form data, encodes it for transmission, sends it to the server,
    
  63. and then receives back its response.
    
  64. 
    
  65. ``GET``, by contrast, bundles the submitted data into a string, and uses this
    
  66. to compose a URL. The URL contains the address where the data must be sent, as
    
  67. well as the data keys and values. You can see this in action if you do a search
    
  68. in the Django documentation, which will produce a URL of the form
    
  69. ``https://docs.djangoproject.com/search/?q=forms&release=1``.
    
  70. 
    
  71. ``GET`` and ``POST`` are typically used for different purposes.
    
  72. 
    
  73. Any request that could be used to change the state of the system - for example,
    
  74. a request that makes changes in the database - should use ``POST``. ``GET``
    
  75. should be used only for requests that do not affect the state of the system.
    
  76. 
    
  77. ``GET`` would also be unsuitable for a password form, because the password
    
  78. would appear in the URL, and thus, also in browser history and server logs,
    
  79. all in plain text. Neither would it be suitable for large quantities of data,
    
  80. or for binary data, such as an image. A web application that uses ``GET``
    
  81. requests for admin forms is a security risk: it can be easy for an attacker to
    
  82. mimic a form's request to gain access to sensitive parts of the system.
    
  83. ``POST``, coupled with other protections like Django's :doc:`CSRF protection
    
  84. </ref/csrf/>` offers more control over access.
    
  85. 
    
  86. On the other hand, ``GET`` is suitable for things like a web search form,
    
  87. because the URLs that represent a ``GET`` request can easily be bookmarked,
    
  88. shared, or resubmitted.
    
  89. 
    
  90. Django's role in forms
    
  91. ======================
    
  92. 
    
  93. Handling forms is a complex business. Consider Django's admin, where numerous
    
  94. items of data of several different types may need to be prepared for display in
    
  95. a form, rendered as HTML, edited using a convenient interface, returned to the
    
  96. server, validated and cleaned up, and then saved or passed on for further
    
  97. processing.
    
  98. 
    
  99. Django's form functionality can simplify and automate vast portions of this
    
  100. work, and can also do it more securely than most programmers would be able to
    
  101. do in code they wrote themselves.
    
  102. 
    
  103. Django handles three distinct parts of the work involved in forms:
    
  104. 
    
  105. * preparing and restructuring data to make it ready for rendering
    
  106. * creating HTML forms for the data
    
  107. * receiving and processing submitted forms and data from the client
    
  108. 
    
  109. It is *possible* to write code that does all of this manually, but Django can
    
  110. take care of it all for you.
    
  111. 
    
  112. Forms in Django
    
  113. ===============
    
  114. 
    
  115. We've described HTML forms briefly, but an HTML ``<form>`` is just one part of
    
  116. the machinery required.
    
  117. 
    
  118. In the context of a web application, 'form' might refer to that HTML
    
  119. ``<form>``, or to the Django :class:`Form` that produces it, or to the
    
  120. structured data returned when it is submitted, or to the end-to-end working
    
  121. collection of these parts.
    
  122. 
    
  123. The Django :class:`Form` class
    
  124. ------------------------------
    
  125. 
    
  126. At the heart of this system of components is Django's :class:`Form` class. In
    
  127. much the same way that a Django model describes the logical structure of an
    
  128. object, its behavior, and the way its parts are represented to us, a
    
  129. :class:`Form` class describes a form and determines how it works and appears.
    
  130. 
    
  131. In a similar way that a model class's fields map to database fields, a form
    
  132. class's fields map to HTML form ``<input>`` elements. (A :class:`ModelForm`
    
  133. maps a model class's fields to HTML form ``<input>`` elements via a
    
  134. :class:`Form`; this is what the Django admin is based upon.)
    
  135. 
    
  136. A form's fields are themselves classes; they manage form data and perform
    
  137. validation when a form is submitted. A :class:`DateField` and a
    
  138. :class:`FileField` handle very different kinds of data and have to do
    
  139. different things with it.
    
  140. 
    
  141. A form field is represented to a user in the browser as an HTML "widget" - a
    
  142. piece of user interface machinery. Each field type has an appropriate default
    
  143. :doc:`Widget class </ref/forms/widgets/>`, but these can be overridden as
    
  144. required.
    
  145. 
    
  146. Instantiating, processing, and rendering forms
    
  147. ----------------------------------------------
    
  148. 
    
  149. When rendering an object in Django, we generally:
    
  150. 
    
  151. #. get hold of it in the view (fetch it from the database, for example)
    
  152. #. pass it to the template context
    
  153. #. expand it to HTML markup using template variables
    
  154. 
    
  155. Rendering a form in a template involves nearly the same work as rendering any
    
  156. other kind of object, but there are some key differences.
    
  157. 
    
  158. In the case of a model instance that contained no data, it would rarely if ever
    
  159. be useful to do anything with it in a template. On the other hand, it makes
    
  160. perfect sense to render an unpopulated form - that's what we do when we want
    
  161. the user to populate it.
    
  162. 
    
  163. So when we handle a model instance in a view, we typically retrieve it from the
    
  164. database. When we're dealing with a form we typically instantiate it in the
    
  165. view.
    
  166. 
    
  167. When we instantiate a form, we can opt to leave it empty or prepopulate it, for
    
  168. example with:
    
  169. 
    
  170. * data from a saved model instance (as in the case of admin forms for editing)
    
  171. * data that we have collated from other sources
    
  172. * data received from a previous HTML form submission
    
  173. 
    
  174. The last of these cases is the most interesting, because it's what makes it
    
  175. possible for users not just to read a website, but to send information back
    
  176. to it too.
    
  177. 
    
  178. Building a form
    
  179. ===============
    
  180. 
    
  181. The work that needs to be done
    
  182. ------------------------------
    
  183. 
    
  184. Suppose you want to create a simple form on your website, in order to obtain
    
  185. the user's name. You'd need something like this in your template:
    
  186. 
    
  187. .. code-block:: html+django
    
  188. 
    
  189.     <form action="/your-name/" method="post">
    
  190.         <label for="your_name">Your name: </label>
    
  191.         <input id="your_name" type="text" name="your_name" value="{{ current_name }}">
    
  192.         <input type="submit" value="OK">
    
  193.     </form>
    
  194. 
    
  195. This tells the browser to return the form data to the URL ``/your-name/``, using
    
  196. the ``POST`` method. It will display a text field, labeled "Your name:", and a
    
  197. button marked "OK". If the template context contains a ``current_name``
    
  198. variable, that will be used to pre-fill the ``your_name`` field.
    
  199. 
    
  200. You'll need a view that renders the template containing the HTML form, and
    
  201. that can supply the ``current_name`` field as appropriate.
    
  202. 
    
  203. When the form is submitted, the ``POST`` request which is sent to the server
    
  204. will contain the form data.
    
  205. 
    
  206. Now you'll also need a view corresponding to that ``/your-name/`` URL which will
    
  207. find the appropriate key/value pairs in the request, and then process them.
    
  208. 
    
  209. This is a very simple form. In practice, a form might contain dozens or
    
  210. hundreds of fields, many of which might need to be prepopulated, and we might
    
  211. expect the user to work through the edit-submit cycle several times before
    
  212. concluding the operation.
    
  213. 
    
  214. We might require some validation to occur in the browser, even before the form
    
  215. is submitted; we might want to use much more complex fields, that allow the
    
  216. user to do things like pick dates from a calendar and so on.
    
  217. 
    
  218. At this point it's much easier to get Django to do most of this work for us.
    
  219. 
    
  220. Building a form in Django
    
  221. -------------------------
    
  222. 
    
  223. The :class:`Form` class
    
  224. ~~~~~~~~~~~~~~~~~~~~~~~
    
  225. 
    
  226. We already know what we want our HTML form to look like. Our starting point for
    
  227. it in Django is this:
    
  228. 
    
  229. .. code-block:: python
    
  230.     :caption: ``forms.py``
    
  231. 
    
  232.     from django import forms
    
  233. 
    
  234.     class NameForm(forms.Form):
    
  235.         your_name = forms.CharField(label='Your name', max_length=100)
    
  236. 
    
  237. This defines a :class:`Form` class with a single field (``your_name``). We've
    
  238. applied a human-friendly label to the field, which will appear in the
    
  239. ``<label>`` when it's rendered (although in this case, the :attr:`~Field.label`
    
  240. we specified is actually the same one that would be generated automatically if
    
  241. we had omitted it).
    
  242. 
    
  243. The field's maximum allowable length is defined by
    
  244. :attr:`~CharField.max_length`. This does two things. It puts a
    
  245. ``maxlength="100"`` on the HTML ``<input>`` (so the browser should prevent the
    
  246. user from entering more than that number of characters in the first place). It
    
  247. also means that when Django receives the form back from the browser, it will
    
  248. validate the length of the data.
    
  249. 
    
  250. A :class:`Form` instance has an :meth:`~Form.is_valid()` method, which runs
    
  251. validation routines for all its fields. When this method is called, if all
    
  252. fields contain valid data, it will:
    
  253. 
    
  254. * return ``True``
    
  255. * place the form's data in its :attr:`~Form.cleaned_data` attribute.
    
  256. 
    
  257. The whole form, when rendered for the first time, will look like:
    
  258. 
    
  259. .. code-block:: html+django
    
  260. 
    
  261.     <label for="your_name">Your name: </label>
    
  262.     <input id="your_name" type="text" name="your_name" maxlength="100" required>
    
  263. 
    
  264. Note that it **does not** include the ``<form>`` tags, or a submit button.
    
  265. We'll have to provide those ourselves in the template.
    
  266. 
    
  267. .. _using-a-form-in-a-view:
    
  268. 
    
  269. The view
    
  270. ~~~~~~~~
    
  271. 
    
  272. Form data sent back to a Django website is processed by a view, generally the
    
  273. same view which published the form. This allows us to reuse some of the same
    
  274. logic.
    
  275. 
    
  276. To handle the form we need to instantiate it in the view for the URL where we
    
  277. want it to be published:
    
  278. 
    
  279. .. code-block:: python
    
  280.     :caption: ``views.py``
    
  281. 
    
  282.     from django.http import HttpResponseRedirect
    
  283.     from django.shortcuts import render
    
  284. 
    
  285.     from .forms import NameForm
    
  286. 
    
  287.     def get_name(request):
    
  288.         # if this is a POST request we need to process the form data
    
  289.         if request.method == 'POST':
    
  290.             # create a form instance and populate it with data from the request:
    
  291.             form = NameForm(request.POST)
    
  292.             # check whether it's valid:
    
  293.             if form.is_valid():
    
  294.                 # process the data in form.cleaned_data as required
    
  295.                 # ...
    
  296.                 # redirect to a new URL:
    
  297.                 return HttpResponseRedirect('/thanks/')
    
  298. 
    
  299.         # if a GET (or any other method) we'll create a blank form
    
  300.         else:
    
  301.             form = NameForm()
    
  302. 
    
  303.         return render(request, 'name.html', {'form': form})
    
  304. 
    
  305. If we arrive at this view with a ``GET`` request, it will create an empty form
    
  306. instance and place it in the template context to be rendered. This is what we
    
  307. can expect to happen the first time we visit the URL.
    
  308. 
    
  309. If the form is submitted using a ``POST`` request, the view will once again
    
  310. create a form instance and populate it with data from the request: ``form =
    
  311. NameForm(request.POST)`` This is called "binding data to the form" (it is now
    
  312. a *bound* form).
    
  313. 
    
  314. We call the form's ``is_valid()`` method; if it's not ``True``, we go back to
    
  315. the template with the form. This time the form is no longer empty (*unbound*)
    
  316. so the HTML form will be populated with the data previously submitted, where it
    
  317. can be edited and corrected as required.
    
  318. 
    
  319. If ``is_valid()`` is ``True``, we'll now be able to find all the validated form
    
  320. data in its ``cleaned_data`` attribute. We can use this data to update the
    
  321. database or do other processing before sending an HTTP redirect to the browser
    
  322. telling it where to go next.
    
  323. 
    
  324. .. _topics-forms-index-basic-form-template:
    
  325. 
    
  326. The template
    
  327. ~~~~~~~~~~~~
    
  328. 
    
  329. We don't need to do much in our ``name.html`` template:
    
  330. 
    
  331. .. code-block:: html+django
    
  332. 
    
  333.     <form action="/your-name/" method="post">
    
  334.         {% csrf_token %}
    
  335.         {{ form }}
    
  336.         <input type="submit" value="Submit">
    
  337.     </form>
    
  338. 
    
  339. All the form's fields and their attributes will be unpacked into HTML markup
    
  340. from that ``{{ form }}`` by Django's template language.
    
  341. 
    
  342. .. admonition:: Forms and Cross Site Request Forgery protection
    
  343. 
    
  344.     Django ships with an easy-to-use :doc:`protection against Cross Site Request
    
  345.     Forgeries </ref/csrf>`. When submitting a form via ``POST`` with
    
  346.     CSRF protection enabled you must use the :ttag:`csrf_token` template tag
    
  347.     as in the preceding example. However, since CSRF protection is not
    
  348.     directly tied to forms in templates, this tag is omitted from the
    
  349.     following examples in this document.
    
  350. 
    
  351. .. admonition:: HTML5 input types and browser validation
    
  352. 
    
  353.     If your form includes a :class:`~django.forms.URLField`, an
    
  354.     :class:`~django.forms.EmailField` or any integer field type, Django will
    
  355.     use the ``url``, ``email`` and ``number`` HTML5 input types. By default,
    
  356.     browsers may apply their own validation on these fields, which may be
    
  357.     stricter than Django's validation. If you would like to disable this
    
  358.     behavior, set the ``novalidate`` attribute on the ``form`` tag, or specify
    
  359.     a different widget on the field, like :class:`TextInput`.
    
  360. 
    
  361. We now have a working web form, described by a Django :class:`Form`, processed
    
  362. by a view, and rendered as an HTML ``<form>``.
    
  363. 
    
  364. That's all you need to get started, but the forms framework puts a lot more at
    
  365. your fingertips. Once you understand the basics of the process described above,
    
  366. you should be prepared to understand other features of the forms system and
    
  367. ready to learn a bit more about the underlying machinery.
    
  368. 
    
  369. More about Django :class:`Form` classes
    
  370. =======================================
    
  371. 
    
  372. All form classes are created as subclasses of either :class:`django.forms.Form`
    
  373. or :class:`django.forms.ModelForm`. You can think of ``ModelForm`` as a
    
  374. subclass of ``Form``. ``Form`` and ``ModelForm`` actually inherit common
    
  375. functionality from a (private) ``BaseForm`` class, but this implementation
    
  376. detail is rarely important.
    
  377. 
    
  378. .. admonition:: Models and Forms
    
  379. 
    
  380.     In fact if your form is going to be used to directly add or edit a Django
    
  381.     model, a :doc:`ModelForm </topics/forms/modelforms>` can save you a great
    
  382.     deal of time, effort, and code, because it will build a form, along with the
    
  383.     appropriate fields and their attributes, from a ``Model`` class.
    
  384. 
    
  385. Bound and unbound form instances
    
  386. --------------------------------
    
  387. 
    
  388. The distinction between :ref:`ref-forms-api-bound-unbound` is important:
    
  389. 
    
  390. * An unbound form has no data associated with it. When rendered to the user,
    
  391.   it will be empty or will contain default values.
    
  392. 
    
  393. * A bound form has submitted data, and hence can be used to tell if that data
    
  394.   is valid. If an invalid bound form is rendered, it can include inline error
    
  395.   messages telling the user what data to correct.
    
  396. 
    
  397. The form's :attr:`~Form.is_bound` attribute will tell you whether a form has
    
  398. data bound to it or not.
    
  399. 
    
  400. More on fields
    
  401. --------------
    
  402. 
    
  403. Consider a more useful form than our minimal example above, which we could use
    
  404. to implement "contact me" functionality on a personal website:
    
  405. 
    
  406. .. code-block:: python
    
  407.     :caption: ``forms.py``
    
  408. 
    
  409.     from django import forms
    
  410. 
    
  411.     class ContactForm(forms.Form):
    
  412.         subject = forms.CharField(max_length=100)
    
  413.         message = forms.CharField(widget=forms.Textarea)
    
  414.         sender = forms.EmailField()
    
  415.         cc_myself = forms.BooleanField(required=False)
    
  416. 
    
  417. Our earlier form used a single field, ``your_name``, a :class:`CharField`. In
    
  418. this case, our form has four fields: ``subject``, ``message``, ``sender`` and
    
  419. ``cc_myself``. :class:`CharField`, :class:`EmailField` and
    
  420. :class:`BooleanField` are just three of the available field types; a full list
    
  421. can be found in :doc:`/ref/forms/fields`.
    
  422. 
    
  423. Widgets
    
  424. ~~~~~~~
    
  425. 
    
  426. Each form field has a corresponding :doc:`Widget class </ref/forms/widgets/>`,
    
  427. which in turn corresponds to an HTML form widget such as ``<input
    
  428. type="text">``.
    
  429. 
    
  430. In most cases, the field will have a sensible default widget. For example, by
    
  431. default, a :class:`CharField` will have a :class:`TextInput` widget, that
    
  432. produces an ``<input type="text">`` in the HTML. If you needed ``<textarea>``
    
  433. instead, you'd specify the appropriate widget when defining your form field,
    
  434. as we have done for the ``message`` field.
    
  435. 
    
  436. Field data
    
  437. ~~~~~~~~~~
    
  438. 
    
  439. Whatever the data submitted with a form, once it has been successfully
    
  440. validated by calling ``is_valid()`` (and ``is_valid()`` has returned ``True``),
    
  441. the validated form data will be in the ``form.cleaned_data`` dictionary. This
    
  442. data will have been nicely converted into Python types for you.
    
  443. 
    
  444. .. note::
    
  445. 
    
  446.     You can still access the unvalidated data directly from ``request.POST`` at
    
  447.     this point, but the validated data is better.
    
  448. 
    
  449. In the contact form example above, ``cc_myself`` will be a boolean value.
    
  450. Likewise, fields such as :class:`IntegerField` and :class:`FloatField` convert
    
  451. values to a Python ``int`` and ``float`` respectively.
    
  452. 
    
  453. Here's how the form data could be processed in the view that handles this form:
    
  454. 
    
  455. .. code-block:: python
    
  456.     :caption: ``views.py``
    
  457. 
    
  458.     from django.core.mail import send_mail
    
  459. 
    
  460.     if form.is_valid():
    
  461.         subject = form.cleaned_data['subject']
    
  462.         message = form.cleaned_data['message']
    
  463.         sender = form.cleaned_data['sender']
    
  464.         cc_myself = form.cleaned_data['cc_myself']
    
  465. 
    
  466.         recipients = ['[email protected]']
    
  467.         if cc_myself:
    
  468.             recipients.append(sender)
    
  469. 
    
  470.         send_mail(subject, message, sender, recipients)
    
  471.         return HttpResponseRedirect('/thanks/')
    
  472. 
    
  473. .. tip::
    
  474. 
    
  475.     For more on sending email from Django, see :doc:`/topics/email`.
    
  476. 
    
  477. Some field types need some extra handling. For example, files that are uploaded
    
  478. using a form need to be handled differently (they can be retrieved from
    
  479. ``request.FILES``, rather than ``request.POST``). For details of how to handle
    
  480. file uploads with your form, see :ref:`binding-uploaded-files`.
    
  481. 
    
  482. Working with form templates
    
  483. ===========================
    
  484. 
    
  485. All you need to do to get your form into a template is to place the form
    
  486. instance into the template context. So if your form is called ``form`` in the
    
  487. context, ``{{ form }}`` will render its ``<label>`` and ``<input>`` elements
    
  488. appropriately.
    
  489. 
    
  490. .. admonition:: Additional form template furniture
    
  491. 
    
  492.     Don't forget that a form's output does *not* include the surrounding
    
  493.     ``<form>`` tags, or the form's ``submit`` control. You will have to provide
    
  494.     these yourself.
    
  495. 
    
  496. Reusable form templates
    
  497. -----------------------
    
  498. 
    
  499. The HTML output when rendering a form is itself generated via a template. You
    
  500. can control this by creating an appropriate template file and setting a custom
    
  501. :setting:`FORM_RENDERER` to use that
    
  502. :attr:`~django.forms.renderers.BaseRenderer.form_template_name` site-wide. You
    
  503. can also customize per-form by overriding the form's
    
  504. :attr:`~django.forms.Form.template_name` attribute to render the form using the
    
  505. custom template, or by passing the template name directly to
    
  506. :meth:`.Form.render`.
    
  507. 
    
  508. The example below will result in ``{{ form }}`` being rendered as the output of
    
  509. the ``form_snippet.html`` template.
    
  510. 
    
  511. In your templates:
    
  512. 
    
  513. .. code-block:: html+django
    
  514. 
    
  515.     # In your template:
    
  516.     {{ form }}
    
  517. 
    
  518.     # In form_snippet.html:
    
  519.     {% for field in form %}
    
  520.         <div class="fieldWrapper">
    
  521.             {{ field.errors }}
    
  522.             {{ field.label_tag }} {{ field }}
    
  523.         </div>
    
  524.     {% endfor %}
    
  525. 
    
  526. Then you can configure the :setting:`FORM_RENDERER` setting:
    
  527. 
    
  528. .. code-block:: python
    
  529.     :caption: ``settings.py``
    
  530. 
    
  531.     from django.forms.renderers import TemplatesSetting
    
  532. 
    
  533.     class CustomFormRenderer(TemplatesSetting):
    
  534.         form_template_name = "form_snippet.html"
    
  535. 
    
  536.     FORM_RENDERER = "project.settings.CustomFormRenderer"
    
  537. 
    
  538. … or for a single form::
    
  539. 
    
  540.     class MyForm(forms.Form):
    
  541.         template_name = "form_snippet.html"
    
  542.         ...
    
  543. 
    
  544. … or for a single render of a form instance, passing in the template name to
    
  545. the :meth:`.Form.render`. Here's an example of this being used in a view::
    
  546. 
    
  547.     def index(request):
    
  548.         form = MyForm()
    
  549.         rendered_form = form.render("form_snippet.html")
    
  550.         context = {'form': rendered_form}
    
  551.         return render(request, 'index.html', context)
    
  552. 
    
  553. See :ref:`ref-forms-api-outputting-html` for more details.
    
  554. 
    
  555. .. versionchanged:: 4.0
    
  556. 
    
  557.     Template rendering of forms was added.
    
  558. 
    
  559. .. versionchanged:: 4.1
    
  560. 
    
  561.     The ability to set the default ``form_template_name`` on the form renderer
    
  562.     was added.
    
  563. 
    
  564. Form rendering options
    
  565. ----------------------
    
  566. 
    
  567. There are other output options though for the ``<label>``/``<input>`` pairs:
    
  568. 
    
  569. * ``{{ form.as_div }}`` will render them wrapped in ``<div>`` tags.
    
  570. 
    
  571. * ``{{ form.as_table }}`` will render them as table cells wrapped in ``<tr>``
    
  572.   tags.
    
  573. 
    
  574. * ``{{ form.as_p }}`` will render them wrapped in ``<p>`` tags.
    
  575. 
    
  576. * ``{{ form.as_ul }}`` will render them wrapped in ``<li>`` tags.
    
  577. 
    
  578. Note that you'll have to provide the surrounding ``<table>`` or ``<ul>``
    
  579. elements yourself.
    
  580. 
    
  581. Here's the output of ``{{ form.as_p }}`` for our ``ContactForm`` instance:
    
  582. 
    
  583. .. code-block:: html+django
    
  584. 
    
  585.     <p><label for="id_subject">Subject:</label>
    
  586.         <input id="id_subject" type="text" name="subject" maxlength="100" required></p>
    
  587.     <p><label for="id_message">Message:</label>
    
  588.         <textarea name="message" id="id_message" required></textarea></p>
    
  589.     <p><label for="id_sender">Sender:</label>
    
  590.         <input type="email" name="sender" id="id_sender" required></p>
    
  591.     <p><label for="id_cc_myself">Cc myself:</label>
    
  592.         <input type="checkbox" name="cc_myself" id="id_cc_myself"></p>
    
  593. 
    
  594. Note that each form field has an ID attribute set to ``id_<field-name>``, which
    
  595. is referenced by the accompanying label tag. This is important in ensuring that
    
  596. forms are accessible to assistive technology such as screen reader software.
    
  597. You can also :ref:`customize the way in which labels and ids are generated
    
  598. <ref-forms-api-configuring-label>`.
    
  599. 
    
  600. See :ref:`ref-forms-api-outputting-html` for more on this.
    
  601. 
    
  602. Rendering fields manually
    
  603. -------------------------
    
  604. 
    
  605. We don't have to let Django unpack the form's fields; we can do it manually if
    
  606. we like (allowing us to reorder the fields, for example). Each field is
    
  607. available as an attribute of the form using ``{{ form.name_of_field }}``, and
    
  608. in a Django template, will be rendered appropriately. For example:
    
  609. 
    
  610. .. code-block:: html+django
    
  611. 
    
  612.     {{ form.non_field_errors }}
    
  613.     <div class="fieldWrapper">
    
  614.         {{ form.subject.errors }}
    
  615.         <label for="{{ form.subject.id_for_label }}">Email subject:</label>
    
  616.         {{ form.subject }}
    
  617.     </div>
    
  618.     <div class="fieldWrapper">
    
  619.         {{ form.message.errors }}
    
  620.         <label for="{{ form.message.id_for_label }}">Your message:</label>
    
  621.         {{ form.message }}
    
  622.     </div>
    
  623.     <div class="fieldWrapper">
    
  624.         {{ form.sender.errors }}
    
  625.         <label for="{{ form.sender.id_for_label }}">Your email address:</label>
    
  626.         {{ form.sender }}
    
  627.     </div>
    
  628.     <div class="fieldWrapper">
    
  629.         {{ form.cc_myself.errors }}
    
  630.         <label for="{{ form.cc_myself.id_for_label }}">CC yourself?</label>
    
  631.         {{ form.cc_myself }}
    
  632.     </div>
    
  633. 
    
  634. Complete ``<label>`` elements can also be generated using the
    
  635. :meth:`~django.forms.BoundField.label_tag`. For example:
    
  636. 
    
  637. .. code-block:: html+django
    
  638. 
    
  639.     <div class="fieldWrapper">
    
  640.         {{ form.subject.errors }}
    
  641.         {{ form.subject.label_tag }}
    
  642.         {{ form.subject }}
    
  643.     </div>
    
  644. 
    
  645. 
    
  646. Rendering form error messages
    
  647. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  648. 
    
  649. The price of this flexibility is a bit more work. Until now we haven't had to
    
  650. worry about how to display form errors, because that's taken care of for us. In
    
  651. this example we have had to make sure we take care of any errors for each field
    
  652. and any errors for the form as a whole. Note ``{{ form.non_field_errors }}`` at
    
  653. the top of the form and the template lookup for errors on each field.
    
  654. 
    
  655. Using ``{{ form.name_of_field.errors }}`` displays a list of form errors,
    
  656. rendered as an unordered list. This might look like:
    
  657. 
    
  658. .. code-block:: html+django
    
  659. 
    
  660.     <ul class="errorlist">
    
  661.         <li>Sender is required.</li>
    
  662.     </ul>
    
  663. 
    
  664. The list has a CSS class of ``errorlist`` to allow you to style its appearance.
    
  665. If you wish to further customize the display of errors you can do so by looping
    
  666. over them:
    
  667. 
    
  668. .. code-block:: html+django
    
  669. 
    
  670.     {% if form.subject.errors %}
    
  671.         <ol>
    
  672.         {% for error in form.subject.errors %}
    
  673.             <li><strong>{{ error|escape }}</strong></li>
    
  674.         {% endfor %}
    
  675.         </ol>
    
  676.     {% endif %}
    
  677. 
    
  678. Non-field errors (and/or hidden field errors that are rendered at the top of
    
  679. the form when using helpers like ``form.as_p()``) will be rendered with an
    
  680. additional class of ``nonfield`` to help distinguish them from field-specific
    
  681. errors. For example, ``{{ form.non_field_errors }}`` would look like:
    
  682. 
    
  683. .. code-block:: html+django
    
  684. 
    
  685.     <ul class="errorlist nonfield">
    
  686.         <li>Generic validation error</li>
    
  687.     </ul>
    
  688. 
    
  689. See :doc:`/ref/forms/api` for more on errors, styling, and working with form
    
  690. attributes in templates.
    
  691. 
    
  692. Looping over the form's fields
    
  693. ------------------------------
    
  694. 
    
  695. If you're using the same HTML for each of your form fields, you can reduce
    
  696. duplicate code by looping through each field in turn using a ``{% for %}``
    
  697. loop:
    
  698. 
    
  699. .. code-block:: html+django
    
  700. 
    
  701.     {% for field in form %}
    
  702.         <div class="fieldWrapper">
    
  703.             {{ field.errors }}
    
  704.             {{ field.label_tag }} {{ field }}
    
  705.             {% if field.help_text %}
    
  706.             <p class="help">{{ field.help_text|safe }}</p>
    
  707.             {% endif %}
    
  708.         </div>
    
  709.     {% endfor %}
    
  710. 
    
  711. Useful attributes on ``{{ field }}`` include:
    
  712. 
    
  713. ``{{ field.errors }}``
    
  714.     Outputs a ``<ul class="errorlist">`` containing any validation errors
    
  715.     corresponding to this field. You can customize the presentation of
    
  716.     the errors with a ``{% for error in field.errors %}`` loop. In this
    
  717.     case, each object in the loop is a string containing the error message.
    
  718. 
    
  719. ``{{ field.field }}``
    
  720.     The :class:`~django.forms.Field` instance from the form class that
    
  721.     this :class:`~django.forms.BoundField` wraps. You can use it to access
    
  722.     :class:`~django.forms.Field` attributes, e.g.
    
  723.     ``{{ char_field.field.max_length }}``.
    
  724. 
    
  725. ``{{ field.help_text }}``
    
  726.     Any help text that has been associated with the field.
    
  727. 
    
  728. ``{{ field.html_name }}``
    
  729.     The name of the field that will be used in the input element's name
    
  730.     field. This takes the form prefix into account, if it has been set.
    
  731. 
    
  732. ``{{ field.id_for_label }}``
    
  733.     The ID that will be used for this field (``id_email`` in the example
    
  734.     above). If you are constructing the label manually, you may want to use
    
  735.     this in lieu of ``label_tag``. It's also useful, for example, if you have
    
  736.     some inline JavaScript and want to avoid hardcoding the field's ID.
    
  737. 
    
  738. ``{{ field.is_hidden }}``
    
  739.     This attribute is ``True`` if the form field is a hidden field and
    
  740.     ``False`` otherwise. It's not particularly useful as a template
    
  741.     variable, but could be useful in conditional tests such as:
    
  742. 
    
  743. .. code-block:: html+django
    
  744. 
    
  745.     {% if field.is_hidden %}
    
  746.        {# Do something special #}
    
  747.     {% endif %}
    
  748. 
    
  749. ``{{ field.label }}``
    
  750.     The label of the field, e.g. ``Email address``.
    
  751. 
    
  752. ``{{ field.label_tag }}``
    
  753.     The field's label wrapped in the appropriate HTML ``<label>`` tag. This
    
  754.     includes the form's :attr:`~django.forms.Form.label_suffix`. For example,
    
  755.     the default ``label_suffix`` is a colon::
    
  756. 
    
  757.         <label for="id_email">Email address:</label>
    
  758. 
    
  759. ``{{ field.legend_tag }}``
    
  760. 
    
  761.     .. versionadded:: 4.1
    
  762. 
    
  763.     Similar to ``field.label_tag`` but uses a ``<legend>`` tag in place of
    
  764.     ``<label>``, for widgets with multiple inputs wrapped in a ``<fieldset>``.
    
  765. 
    
  766. ``{{ field.use_fieldset }}``
    
  767. 
    
  768.     .. versionadded:: 4.1
    
  769. 
    
  770.     This attribute is ``True`` if the form field's widget contains multiple
    
  771.     inputs that should be semantically grouped in a ``<fieldset>`` with a
    
  772.     ``<legend>`` to improve accessibility. An example use in a template:
    
  773. 
    
  774. .. code-block:: html+django
    
  775. 
    
  776.     {% if field.use_fieldset %}
    
  777.       <fieldset>
    
  778.       {% if field.label %}{{ field.legend_tag }}{% endif %}
    
  779.     {% else %}
    
  780.       {% if field.label %}{{ field.label_tag }}{% endif %}
    
  781.     {% endif %}
    
  782.     {{ field }}
    
  783.     {% if field.use_fieldset %}</fieldset>{% endif %}
    
  784. 
    
  785. ``{{ field.value }}``
    
  786.     The value of the field. e.g ``[email protected]``.
    
  787. 
    
  788. .. seealso::
    
  789. 
    
  790.     For a complete list of attributes and methods, see
    
  791.     :class:`~django.forms.BoundField`.
    
  792. 
    
  793. Looping over hidden and visible fields
    
  794. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  795. 
    
  796. If you're manually laying out a form in a template, as opposed to relying on
    
  797. Django's default form layout, you might want to treat ``<input type="hidden">``
    
  798. fields differently from non-hidden fields. For example, because hidden fields
    
  799. don't display anything, putting error messages "next to" the field could cause
    
  800. confusion for your users -- so errors for those fields should be handled
    
  801. differently.
    
  802. 
    
  803. Django provides two methods on a form that allow you to loop over the hidden
    
  804. and visible fields independently: ``hidden_fields()`` and
    
  805. ``visible_fields()``. Here's a modification of an earlier example that uses
    
  806. these two methods:
    
  807. 
    
  808. .. code-block:: html+django
    
  809. 
    
  810.     {# Include the hidden fields #}
    
  811.     {% for hidden in form.hidden_fields %}
    
  812.     {{ hidden }}
    
  813.     {% endfor %}
    
  814.     {# Include the visible fields #}
    
  815.     {% for field in form.visible_fields %}
    
  816.         <div class="fieldWrapper">
    
  817.             {{ field.errors }}
    
  818.             {{ field.label_tag }} {{ field }}
    
  819.         </div>
    
  820.     {% endfor %}
    
  821. 
    
  822. This example does not handle any errors in the hidden fields. Usually, an
    
  823. error in a hidden field is a sign of form tampering, since normal form
    
  824. interaction won't alter them. However, you could easily insert some error
    
  825. displays for those form errors, as well.
    
  826. 
    
  827. Further topics
    
  828. ==============
    
  829. 
    
  830. This covers the basics, but forms can do a whole lot more:
    
  831. 
    
  832. .. toctree::
    
  833.    :maxdepth: 2
    
  834. 
    
  835.    formsets
    
  836.    modelforms
    
  837.    media
    
  838. 
    
  839. .. seealso::
    
  840. 
    
  841.     :doc:`The Forms Reference </ref/forms/index>`
    
  842.         Covers the full API reference, including form fields, form widgets,
    
  843.         and form and field validation.