index.txt 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. ==================
  2. Working with forms
  3. ==================
  4. .. admonition:: About this document
  5. This document provides an introduction to Django's form handling features.
  6. For a more detailed look at specific areas of the forms API, see
  7. :doc:`/ref/forms/api`, :doc:`/ref/forms/fields`, and
  8. :doc:`/ref/forms/validation`.
  9. .. highlightlang:: html+django
  10. ``django.forms`` is Django's form-handling library.
  11. While it is possible to process form submissions just using Django's
  12. :class:`~django.http.HttpRequest` class, using the form library takes care of a
  13. number of common form-related tasks. Using it, you can:
  14. 1. Display an HTML form with automatically generated form widgets.
  15. 2. Check submitted data against a set of validation rules.
  16. 3. Redisplay a form in the case of validation errors.
  17. 4. Convert submitted form data to the relevant Python data types.
  18. Overview
  19. ========
  20. The library deals with these concepts:
  21. .. glossary::
  22. Widget
  23. A class that corresponds to an HTML form widget, e.g.
  24. ``<input type="text">`` or ``<textarea>``. This handles rendering of the
  25. widget as HTML.
  26. Field
  27. A class that is responsible for doing validation, e.g.
  28. an ``EmailField`` that makes sure its data is a valid email address.
  29. Form
  30. A collection of fields that knows how to validate itself and
  31. display itself as HTML.
  32. Form Assets (the ``Media`` class)
  33. The CSS and JavaScript resources that are required to render a form.
  34. The library is decoupled from the other Django components, such as the database
  35. layer, views and templates. It relies only on Django settings, a couple of
  36. ``django.utils`` helper functions and Django's internationalization hooks (but
  37. you're not required to be using internationalization features to use this
  38. library).
  39. Form objects
  40. ============
  41. A Form object encapsulates a sequence of form fields and a collection of
  42. validation rules that must be fulfilled in order for the form to be accepted.
  43. Form classes are created as subclasses of ``django.forms.Form`` and
  44. make use of a declarative style that you'll be familiar with if you've used
  45. Django's database models.
  46. For example, consider a form used to implement "contact me" functionality on a
  47. personal Web site:
  48. .. code-block:: python
  49. from django import forms
  50. class ContactForm(forms.Form):
  51. subject = forms.CharField(max_length=100)
  52. message = forms.CharField()
  53. sender = forms.EmailField()
  54. cc_myself = forms.BooleanField(required=False)
  55. A form is composed of ``Field`` objects. In this case, our form has four
  56. fields: ``subject``, ``message``, ``sender`` and ``cc_myself``. ``CharField``,
  57. ``EmailField`` and ``BooleanField`` are just three of the available field types;
  58. a full list can be found in :doc:`/ref/forms/fields`.
  59. If your form is going to be used to directly add or edit a Django model, you can
  60. use a :doc:`ModelForm </topics/forms/modelforms>` to avoid duplicating your model
  61. description.
  62. .. _using-a-form-in-a-view:
  63. Using a form in a view
  64. ----------------------
  65. The standard pattern for processing a form in a view looks like this:
  66. .. code-block:: python
  67. from django.shortcuts import render
  68. from django.http import HttpResponseRedirect
  69. def contact(request):
  70. if request.method == 'POST': # If the form has been submitted...
  71. # ContactForm was defined in the the previous section
  72. form = ContactForm(request.POST) # A form bound to the POST data
  73. if form.is_valid(): # All validation rules pass
  74. # Process the data in form.cleaned_data
  75. # ...
  76. return HttpResponseRedirect('/thanks/') # Redirect after POST
  77. else:
  78. form = ContactForm() # An unbound form
  79. return render(request, 'contact.html', {
  80. 'form': form,
  81. })
  82. There are three possible code paths here:
  83. +------------------+---------------+-----------------------------------------+
  84. | Form submitted? | Data? | What occurs |
  85. +==================+===============+=========================================+
  86. | Not submitted | None yet | Template gets passed unbound instance |
  87. | | | of ContactForm. |
  88. +------------------+---------------+-----------------------------------------+
  89. | Submitted | Invalid data | Template gets passed bound instance |
  90. | | | of ContactForm. |
  91. +------------------+---------------+-----------------------------------------+
  92. | Submitted | Valid data | Valid data is processed. Redirect to a |
  93. | | | "thanks" page. |
  94. +------------------+---------------+-----------------------------------------+
  95. The distinction between :ref:`ref-forms-api-bound-unbound` is important:
  96. * An unbound form has no data associated with it. When rendered to the user,
  97. it will be empty or will contain default values.
  98. * A bound form has submitted data, and hence can be used to tell if that data
  99. is valid. If an invalid bound form is rendered, it can include inline error
  100. messages telling the user what data to correct.
  101. Handling file uploads with a form
  102. ---------------------------------
  103. To see how to handle file uploads with your form, see
  104. :ref:`binding-uploaded-files`.
  105. Processing the data from a form
  106. -------------------------------
  107. Once ``is_valid()`` returns ``True``, the successfully validated form data
  108. will be in the ``form.cleaned_data`` dictionary. This data will have been
  109. converted nicely into Python types for you.
  110. .. note::
  111. You can still access the unvalidated data directly from ``request.POST`` at
  112. this point, but the validated data is better.
  113. In the above example, ``cc_myself`` will be a boolean value. Likewise, fields
  114. such as ``IntegerField`` and ``FloatField`` convert values to a Python int and
  115. float respectively.
  116. Read-only fields are not available in ``form.cleaned_data`` (and setting
  117. a value in a custom ``clean()`` method won't have any effect). These
  118. fields are displayed as text rather than as input elements, and thus are not
  119. posted back to the server.
  120. Extending the earlier example, here's how the form data could be processed:
  121. .. code-block:: python
  122. if form.is_valid():
  123. subject = form.cleaned_data['subject']
  124. message = form.cleaned_data['message']
  125. sender = form.cleaned_data['sender']
  126. cc_myself = form.cleaned_data['cc_myself']
  127. recipients = ['info@example.com']
  128. if cc_myself:
  129. recipients.append(sender)
  130. from django.core.mail import send_mail
  131. send_mail(subject, message, sender, recipients)
  132. return HttpResponseRedirect('/thanks/') # Redirect after POST
  133. .. tip::
  134. For more on sending email from Django, see :doc:`/topics/email`.
  135. Displaying a form using a template
  136. ----------------------------------
  137. Forms are designed to work with the Django template language. In the above
  138. example, we passed our ``ContactForm`` instance to the template using the
  139. context variable ``form``. Here's a simple example template::
  140. <form action="/contact/" method="post">{% csrf_token %}
  141. {{ form.as_p }}
  142. <input type="submit" value="Submit" />
  143. </form>
  144. The form only outputs its own fields; it is up to you to provide the surrounding
  145. ``<form>`` tags and the submit button.
  146. If your form includes uploaded files, be sure to include
  147. ``enctype="multipart/form-data"`` in the ``form`` element. If you wish to write
  148. a generic template that will work whether or not the form has files, you can
  149. use the :meth:`~django.forms.Form.is_multipart` attribute on the form::
  150. <form action="/contact/" method="post"
  151. {% if form.is_multipart %}enctype="multipart/form-data"{% endif %}>
  152. .. admonition:: Forms and Cross Site Request Forgery protection
  153. Django ships with an easy-to-use :doc:`protection against Cross Site Request
  154. Forgeries </ref/contrib/csrf>`. When submitting a form via POST with
  155. CSRF protection enabled you must use the :ttag:`csrf_token` template tag
  156. as in the preceding example. However, since CSRF protection is not
  157. directly tied to forms in templates, this tag is omitted from the
  158. following examples in this document.
  159. ``form.as_p`` will output the form with each form field and accompanying label
  160. wrapped in a paragraph. Here's the output for our example template::
  161. <form action="/contact/" method="post">
  162. <p><label for="id_subject">Subject:</label>
  163. <input id="id_subject" type="text" name="subject" maxlength="100" /></p>
  164. <p><label for="id_message">Message:</label>
  165. <input type="text" name="message" id="id_message" /></p>
  166. <p><label for="id_sender">Sender:</label>
  167. <input type="email" name="sender" id="id_sender" /></p>
  168. <p><label for="id_cc_myself">Cc myself:</label>
  169. <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>
  170. <input type="submit" value="Submit" />
  171. </form>
  172. Note that each form field has an ID attribute set to ``id_<field-name>``, which
  173. is referenced by the accompanying label tag. This is important for ensuring
  174. forms are accessible to assistive technology such as screen reader software. You
  175. can also :ref:`customize the way in which labels and ids are generated
  176. <ref-forms-api-configuring-label>`.
  177. You can also use ``form.as_table`` to output table rows (you'll need to provide
  178. your own ``<table>`` tags) and ``form.as_ul`` to output list items.
  179. Customizing the form template
  180. -----------------------------
  181. If the default generated HTML is not to your taste, you can completely customize
  182. the way a form is presented using the Django template language. Extending the
  183. above example::
  184. <form action="/contact/" method="post">
  185. {{ form.non_field_errors }}
  186. <div class="fieldWrapper">
  187. {{ form.subject.errors }}
  188. <label for="id_subject">Email subject:</label>
  189. {{ form.subject }}
  190. </div>
  191. <div class="fieldWrapper">
  192. {{ form.message.errors }}
  193. <label for="id_message">Your message:</label>
  194. {{ form.message }}
  195. </div>
  196. <div class="fieldWrapper">
  197. {{ form.sender.errors }}
  198. <label for="id_sender">Your email address:</label>
  199. {{ form.sender }}
  200. </div>
  201. <div class="fieldWrapper">
  202. {{ form.cc_myself.errors }}
  203. <label for="id_cc_myself">CC yourself?</label>
  204. {{ form.cc_myself }}
  205. </div>
  206. <p><input type="submit" value="Send message" /></p>
  207. </form>
  208. Each named form-field can be output to the template using
  209. ``{{ form.name_of_field }}``, which will produce the HTML needed to display the
  210. form widget. Using ``{{ form.name_of_field.errors }}`` displays a list of form
  211. errors, rendered as an unordered list. This might look like::
  212. <ul class="errorlist">
  213. <li>Sender is required.</li>
  214. </ul>
  215. The list has a CSS class of ``errorlist`` to allow you to style its appearance.
  216. If you wish to further customize the display of errors you can do so by looping
  217. over them::
  218. {% if form.subject.errors %}
  219. <ol>
  220. {% for error in form.subject.errors %}
  221. <li><strong>{{ error|escape }}</strong></li>
  222. {% endfor %}
  223. </ol>
  224. {% endif %}
  225. Looping over the form's fields
  226. ------------------------------
  227. If you're using the same HTML for each of your form fields, you can reduce
  228. duplicate code by looping through each field in turn using a ``{% for %}``
  229. loop::
  230. <form action="/contact/" method="post">
  231. {% for field in form %}
  232. <div class="fieldWrapper">
  233. {{ field.errors }}
  234. {{ field.label_tag }} {{ field }}
  235. </div>
  236. {% endfor %}
  237. <p><input type="submit" value="Send message" /></p>
  238. </form>
  239. Within this loop, ``{{ field }}`` is an instance of
  240. :class:`~django.forms.BoundField`. ``BoundField`` also has the following
  241. attributes, which can be useful in your templates:
  242. ``{{ field.label }}``
  243. The label of the field, e.g. ``Email address``.
  244. ``{{ field.label_tag }}``
  245. The field's label wrapped in the appropriate HTML ``<label>`` tag.
  246. .. versionchanged:: 1.6
  247. This includes the form's :attr:`~django.forms.Form.label_suffix`. For
  248. example, the default ``label_suffix`` is a colon::
  249. <label for="id_email">Email address:</label>
  250. ``{{ field.id_for_label }}``
  251. The ID that will be used for this field (``id_email`` in the example
  252. above). You may want to use this in lieu of ``label_tag`` if you are
  253. constructing the label manually. It's also useful, for example, if you have
  254. some inline JavaScript and want to avoid hardcoding the field's ID.
  255. ``{{ field.value }}``
  256. The value of the field. e.g ``someone@example.com``
  257. ``{{ field.html_name }}``
  258. The name of the field that will be used in the input element's name
  259. field. This takes the form prefix into account, if it has been set.
  260. ``{{ field.help_text }}``
  261. Any help text that has been associated with the field.
  262. ``{{ field.errors }}``
  263. Outputs a ``<ul class="errorlist">`` containing any validation errors
  264. corresponding to this field. You can customize the presentation of
  265. the errors with a ``{% for error in field.errors %}`` loop. In this
  266. case, each object in the loop is a simple string containing the error
  267. message.
  268. ``{{ field.is_hidden }}``
  269. This attribute is ``True`` if the form field is a hidden field and
  270. ``False`` otherwise. It's not particularly useful as a template
  271. variable, but could be useful in conditional tests such as::
  272. {% if field.is_hidden %}
  273. {# Do something special #}
  274. {% endif %}
  275. ``{{ field.field }}``
  276. The :class:`~django.forms.Field` instance from the form class that
  277. this :class:`~django.forms.BoundField` wraps. You can use it to access
  278. :class:`~django.forms.Field` attributes , e.g.
  279. ``{{ char_field.field.max_length }}``.
  280. Looping over hidden and visible fields
  281. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  282. If you're manually laying out a form in a template, as opposed to relying on
  283. Django's default form layout, you might want to treat ``<input type="hidden">``
  284. fields differently than non-hidden fields. For example, because hidden fields
  285. don't display anything, putting error messages "next to" the field could cause
  286. confusion for your users -- so errors for those fields should be handled
  287. differently.
  288. Django provides two methods on a form that allow you to loop over the hidden
  289. and visible fields independently: ``hidden_fields()`` and
  290. ``visible_fields()``. Here's a modification of an earlier example that uses
  291. these two methods::
  292. <form action="/contact/" method="post">
  293. {# Include the hidden fields #}
  294. {% for hidden in form.hidden_fields %}
  295. {{ hidden }}
  296. {% endfor %}
  297. {# Include the visible fields #}
  298. {% for field in form.visible_fields %}
  299. <div class="fieldWrapper">
  300. {{ field.errors }}
  301. {{ field.label_tag }} {{ field }}
  302. </div>
  303. {% endfor %}
  304. <p><input type="submit" value="Send message" /></p>
  305. </form>
  306. This example does not handle any errors in the hidden fields. Usually, an
  307. error in a hidden field is a sign of form tampering, since normal form
  308. interaction won't alter them. However, you could easily insert some error
  309. displays for those form errors, as well.
  310. Reusable form templates
  311. -----------------------
  312. If your site uses the same rendering logic for forms in multiple places, you
  313. can reduce duplication by saving the form's loop in a standalone template and
  314. using the :ttag:`include` tag to reuse it in other templates::
  315. <form action="/contact/" method="post">
  316. {% include "form_snippet.html" %}
  317. <p><input type="submit" value="Send message" /></p>
  318. </form>
  319. # In form_snippet.html:
  320. {% for field in form %}
  321. <div class="fieldWrapper">
  322. {{ field.errors }}
  323. {{ field.label_tag }} {{ field }}
  324. </div>
  325. {% endfor %}
  326. If the form object passed to a template has a different name within the
  327. context, you can alias it using the ``with`` argument of the :ttag:`include`
  328. tag::
  329. <form action="/comments/add/" method="post">
  330. {% include "form_snippet.html" with form=comment_form %}
  331. <p><input type="submit" value="Submit comment" /></p>
  332. </form>
  333. If you find yourself doing this often, you might consider creating a custom
  334. :ref:`inclusion tag<howto-custom-template-tags-inclusion-tags>`.
  335. Further topics
  336. ==============
  337. This covers the basics, but forms can do a whole lot more:
  338. .. toctree::
  339. :maxdepth: 2
  340. formsets
  341. modelforms
  342. media
  343. .. seealso::
  344. :doc:`The Forms Reference </ref/forms/index>`
  345. Covers the full API reference, including form fields, form widgets,
  346. and form and field validation.