index.txt 15 KB

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