index.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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 Media
  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. form = ContactForm(request.POST) # A form bound to the POST data
  72. if form.is_valid(): # All validation rules pass
  73. # Process the data in form.cleaned_data
  74. # ...
  75. return HttpResponseRedirect('/thanks/') # Redirect after POST
  76. else:
  77. form = ContactForm() # An unbound form
  78. return render(request, 'contact.html', {
  79. 'form': form,
  80. })
  81. There are three possible code paths here:
  82. +------------------+---------------+-----------------------------------------+
  83. | Form submitted? | Data? | What occurs |
  84. +==================+===============+=========================================+
  85. | Unsubmitted | None yet | Template gets passed unbound instance |
  86. | | | of ContactForm. |
  87. +------------------+---------------+-----------------------------------------+
  88. | Submitted | Invalid data | Template gets passed bound instance |
  89. | | | of ContactForm. |
  90. +------------------+---------------+-----------------------------------------+
  91. | Submitted | Valid data | Valid data is processed. Redirect to a |
  92. | | | "thanks" page. |
  93. +------------------+---------------+-----------------------------------------+
  94. The distinction between :ref:`ref-forms-api-bound-unbound` is important:
  95. * An unbound form has no data associated with it. When rendered to the user,
  96. it will be empty or will contain default values.
  97. * A bound form has submitted data, and hence can be used to tell if that data
  98. is valid. If an invalid bound form is rendered, it can include inline error
  99. messages telling the user what data to correct.
  100. Handling file uploads with a form
  101. ---------------------------------
  102. To see how to handle file uploads with your form, see
  103. :ref:`binding-uploaded-files`.
  104. Processing the data from a form
  105. -------------------------------
  106. Once ``is_valid()`` returns ``True``, the successfully validated form data
  107. will be in the ``form.cleaned_data`` dictionary. This data will have been
  108. converted nicely into Python types for you.
  109. .. note::
  110. You can still access the unvalidated data directly from ``request.POST`` at
  111. this point, but the validated data is better.
  112. In the above example, ``cc_myself`` will be a boolean value. Likewise, fields
  113. such as ``IntegerField`` and ``FloatField`` convert values to a Python int and
  114. float respectively.
  115. Read-only fields are not available in ``form.cleaned_data`` (and setting
  116. a value in a custom ``clean()`` method won't have any effect). These
  117. fields are displayed as text rather than as input elements, and thus are not
  118. posted back to the server.
  119. Extending the earlier example, here's how the form data could be processed:
  120. .. code-block:: python
  121. if form.is_valid():
  122. subject = form.cleaned_data['subject']
  123. message = form.cleaned_data['message']
  124. sender = form.cleaned_data['sender']
  125. cc_myself = form.cleaned_data['cc_myself']
  126. recipients = ['info@example.com']
  127. if cc_myself:
  128. recipients.append(sender)
  129. from django.core.mail import send_mail
  130. send_mail(subject, message, sender, recipients)
  131. return HttpResponseRedirect('/thanks/') # Redirect after POST
  132. .. tip::
  133. For more on sending email from Django, see :doc:`/topics/email`.
  134. Displaying a form using a template
  135. ----------------------------------
  136. Forms are designed to work with the Django template language. In the above
  137. example, we passed our ``ContactForm`` instance to the template using the
  138. context variable ``form``. Here's a simple example template::
  139. <form action="/contact/" method="post">{% csrf_token %}
  140. {{ form.as_p }}
  141. <input type="submit" value="Submit" />
  142. </form>
  143. The form only outputs its own fields; it is up to you to provide the surrounding
  144. ``<form>`` tags and the submit button.
  145. .. admonition:: Forms and Cross Site Request Forgery protection
  146. Django ships with an easy-to-use :doc:`protection against Cross Site Request
  147. Forgeries </ref/contrib/csrf>`. When submitting a form via POST with
  148. CSRF protection enabled you must use the :ttag:`csrf_token` template tag
  149. as in the preceding example. However, since CSRF protection is not
  150. directly tied to forms in templates, this tag is omitted from the
  151. following examples in this document.
  152. ``form.as_p`` will output the form with each form field and accompanying label
  153. wrapped in a paragraph. Here's the output for our example template::
  154. <form action="/contact/" method="post">
  155. <p><label for="id_subject">Subject:</label>
  156. <input id="id_subject" type="text" name="subject" maxlength="100" /></p>
  157. <p><label for="id_message">Message:</label>
  158. <input type="text" name="message" id="id_message" /></p>
  159. <p><label for="id_sender">Sender:</label>
  160. <input type="text" name="sender" id="id_sender" /></p>
  161. <p><label for="id_cc_myself">Cc myself:</label>
  162. <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>
  163. <input type="submit" value="Submit" />
  164. </form>
  165. Note that each form field has an ID attribute set to ``id_<field-name>``, which
  166. is referenced by the accompanying label tag. This is important for ensuring
  167. forms are accessible to assistive technology such as screen reader software. You
  168. can also :ref:`customize the way in which labels and ids are generated
  169. <ref-forms-api-configuring-label>`.
  170. You can also use ``form.as_table`` to output table rows (you'll need to provide
  171. your own ``<table>`` tags) and ``form.as_ul`` to output list items.
  172. Customizing the form template
  173. -----------------------------
  174. If the default generated HTML is not to your taste, you can completely customize
  175. the way a form is presented using the Django template language. Extending the
  176. above example::
  177. <form action="/contact/" method="post">
  178. {{ form.non_field_errors }}
  179. <div class="fieldWrapper">
  180. {{ form.subject.errors }}
  181. <label for="id_subject">Email subject:</label>
  182. {{ form.subject }}
  183. </div>
  184. <div class="fieldWrapper">
  185. {{ form.message.errors }}
  186. <label for="id_message">Your message:</label>
  187. {{ form.message }}
  188. </div>
  189. <div class="fieldWrapper">
  190. {{ form.sender.errors }}
  191. <label for="id_sender">Your email address:</label>
  192. {{ form.sender }}
  193. </div>
  194. <div class="fieldWrapper">
  195. {{ form.cc_myself.errors }}
  196. <label for="id_cc_myself">CC yourself?</label>
  197. {{ form.cc_myself }}
  198. </div>
  199. <p><input type="submit" value="Send message" /></p>
  200. </form>
  201. Each named form-field can be output to the template using
  202. ``{{ form.name_of_field }}``, which will produce the HTML needed to display the
  203. form widget. Using ``{{ form.name_of_field.errors }}`` displays a list of form
  204. errors, rendered as an unordered list. This might look like::
  205. <ul class="errorlist">
  206. <li>Sender is required.</li>
  207. </ul>
  208. The list has a CSS class of ``errorlist`` to allow you to style its appearance.
  209. If you wish to further customize the display of errors you can do so by looping
  210. over them::
  211. {% if form.subject.errors %}
  212. <ol>
  213. {% for error in form.subject.errors %}
  214. <li><strong>{{ error|escape }}</strong></li>
  215. {% endfor %}
  216. </ol>
  217. {% endif %}
  218. Looping over the form's fields
  219. ------------------------------
  220. If you're using the same HTML for each of your form fields, you can reduce
  221. duplicate code by looping through each field in turn using a ``{% for %}``
  222. loop::
  223. <form action="/contact/" method="post">
  224. {% for field in form %}
  225. <div class="fieldWrapper">
  226. {{ field.errors }}
  227. {{ field.label_tag }}: {{ field }}
  228. </div>
  229. {% endfor %}
  230. <p><input type="submit" value="Send message" /></p>
  231. </form>
  232. Within this loop, ``{{ field }}`` is an instance of
  233. :class:`~django.forms.BoundField`. ``BoundField`` also has the following
  234. attributes, which can be useful in your templates:
  235. ``{{ field.label }}``
  236. The label of the field, e.g. ``Email address``.
  237. ``{{ field.label_tag }}``
  238. The field's label wrapped in the appropriate HTML ``<label>`` tag,
  239. e.g. ``<label for="id_email">Email address</label>``
  240. ``{{ field.value }}``
  241. The value of the field. e.g ``someone@example.com``
  242. ``{{ field.html_name }}``
  243. The name of the field that will be used in the input element's name
  244. field. This takes the form prefix into account, if it has been set.
  245. ``{{ field.help_text }}``
  246. Any help text that has been associated with the field.
  247. ``{{ field.errors }}``
  248. Outputs a ``<ul class="errorlist">`` containing any validation errors
  249. corresponding to this field. You can customize the presentation of
  250. the errors with a ``{% for error in field.errors %}`` loop. In this
  251. case, each object in the loop is a simple string containing the error
  252. message.
  253. ``field.is_hidden``
  254. This attribute is ``True`` if the form field is a hidden field and
  255. ``False`` otherwise. It's not particularly useful as a template
  256. variable, but could be useful in conditional tests such as::
  257. {% if field.is_hidden %}
  258. {# Do something special #}
  259. {% endif %}
  260. Looping over hidden and visible fields
  261. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  262. If you're manually laying out a form in a template, as opposed to relying on
  263. Django's default form layout, you might want to treat ``<input type="hidden">``
  264. fields differently than non-hidden fields. For example, because hidden fields
  265. don't display anything, putting error messages "next to" the field could cause
  266. confusion for your users -- so errors for those fields should be handled
  267. differently.
  268. Django provides two methods on a form that allow you to loop over the hidden
  269. and visible fields independently: ``hidden_fields()`` and
  270. ``visible_fields()``. Here's a modification of an earlier example that uses
  271. these two methods::
  272. <form action="/contact/" method="post">
  273. {# Include the hidden fields #}
  274. {% for hidden in form.hidden_fields %}
  275. {{ hidden }}
  276. {% endfor %}
  277. {# Include the visible fields #}
  278. {% for field in form.visible_fields %}
  279. <div class="fieldWrapper">
  280. {{ field.errors }}
  281. {{ field.label_tag }}: {{ field }}
  282. </div>
  283. {% endfor %}
  284. <p><input type="submit" value="Send message" /></p>
  285. </form>
  286. This example does not handle any errors in the hidden fields. Usually, an
  287. error in a hidden field is a sign of form tampering, since normal form
  288. interaction won't alter them. However, you could easily insert some error
  289. displays for those form errors, as well.
  290. Reusable form templates
  291. -----------------------
  292. If your site uses the same rendering logic for forms in multiple places, you
  293. can reduce duplication by saving the form's loop in a standalone template and
  294. using the :ttag:`include` tag to reuse it in other templates::
  295. <form action="/contact/" method="post">
  296. {% include "form_snippet.html" %}
  297. <p><input type="submit" value="Send message" /></p>
  298. </form>
  299. # In form_snippet.html:
  300. {% for field in form %}
  301. <div class="fieldWrapper">
  302. {{ field.errors }}
  303. {{ field.label_tag }}: {{ field }}
  304. </div>
  305. {% endfor %}
  306. If the form object passed to a template has a different name within the
  307. context, you can alias it using the ``with`` argument of the :ttag:`include`
  308. tag::
  309. <form action="/comments/add/" method="post">
  310. {% include "form_snippet.html" with form=comment_form %}
  311. <p><input type="submit" value="Submit comment" /></p>
  312. </form>
  313. If you find yourself doing this often, you might consider creating a custom
  314. :ref:`inclusion tag<howto-custom-template-tags-inclusion-tags>`.
  315. Further topics
  316. ==============
  317. This covers the basics, but forms can do a whole lot more:
  318. .. toctree::
  319. :maxdepth: 2
  320. formsets
  321. modelforms
  322. media
  323. .. seealso::
  324. :doc:`The Forms Reference </ref/forms/index>`
  325. Covers the full API reference, including form fields, form widgets,
  326. and form and field validation.