index.txt 14 KB

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