/docs/topics/forms/index.txt

https://code.google.com/p/mango-py/ · Plain Text · 407 lines · 316 code · 91 blank · 0 comment · 0 complexity · 36fe65695638d0647b1400e637d5e5a7 MD5 · raw file

  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">{% csrf_token %}
  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. .. admonition:: Forms and Cross Site Request Forgery protection
  137. Django ships with an easy-to-use :doc:`protection against Cross Site Request
  138. Forgeries </ref/contrib/csrf>`. When submitting a form via POST with
  139. CSRF protection enabled you must use the :ttag:`csrf_token` template tag
  140. as in the preceding example. However, since CSRF protection is not
  141. directly tied to forms in templates, this tag is omitted from the
  142. following examples in this document.
  143. ``form.as_p`` will output the form with each form field and accompanying label
  144. wrapped in a paragraph. Here's the output for our example template::
  145. <form action="/contact/" method="post">
  146. <p><label for="id_subject">Subject:</label>
  147. <input id="id_subject" type="text" name="subject" maxlength="100" /></p>
  148. <p><label for="id_message">Message:</label>
  149. <input type="text" name="message" id="id_message" /></p>
  150. <p><label for="id_sender">Sender:</label>
  151. <input type="text" name="sender" id="id_sender" /></p>
  152. <p><label for="id_cc_myself">Cc myself:</label>
  153. <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>
  154. <input type="submit" value="Submit" />
  155. </form>
  156. Note that each form field has an ID attribute set to ``id_<field-name>``, which
  157. is referenced by the accompanying label tag. This is important for ensuring
  158. forms are accessible to assistive technology such as screen reader software. You
  159. can also :ref:`customize the way in which labels and ids are generated
  160. <ref-forms-api-configuring-label>`.
  161. You can also use ``form.as_table`` to output table rows (you'll need to provide
  162. your own ``<table>`` tags) and ``form.as_ul`` to output list items.
  163. Customizing the form template
  164. -----------------------------
  165. If the default generated HTML is not to your taste, you can completely customize
  166. the way a form is presented using the Django template language. Extending the
  167. above example::
  168. <form action="/contact/" method="post">
  169. {{ form.non_field_errors }}
  170. <div class="fieldWrapper">
  171. {{ form.subject.errors }}
  172. <label for="id_subject">E-mail subject:</label>
  173. {{ form.subject }}
  174. </div>
  175. <div class="fieldWrapper">
  176. {{ form.message.errors }}
  177. <label for="id_message">Your message:</label>
  178. {{ form.message }}
  179. </div>
  180. <div class="fieldWrapper">
  181. {{ form.sender.errors }}
  182. <label for="id_sender">Your email address:</label>
  183. {{ form.sender }}
  184. </div>
  185. <div class="fieldWrapper">
  186. {{ form.cc_myself.errors }}
  187. <label for="id_cc_myself">CC yourself?</label>
  188. {{ form.cc_myself }}
  189. </div>
  190. <p><input type="submit" value="Send message" /></p>
  191. </form>
  192. Each named form-field can be output to the template using
  193. ``{{ form.name_of_field }}``, which will produce the HTML needed to display the
  194. form widget. Using ``{{ form.name_of_field.errors }}`` displays a list of form
  195. errors, rendered as an unordered list. This might look like::
  196. <ul class="errorlist">
  197. <li>Sender is required.</li>
  198. </ul>
  199. The list has a CSS class of ``errorlist`` to allow you to style its appearance.
  200. If you wish to further customize the display of errors you can do so by looping
  201. over them::
  202. {% if form.subject.errors %}
  203. <ol>
  204. {% for error in form.subject.errors %}
  205. <li><strong>{{ error|escape }}</strong></li>
  206. {% endfor %}
  207. </ol>
  208. {% endif %}
  209. Looping over the form's fields
  210. ------------------------------
  211. If you're using the same HTML for each of your form fields, you can reduce
  212. duplicate code by looping through each field in turn using a ``{% for %}``
  213. loop::
  214. <form action="/contact/" method="post">
  215. {% for field in form %}
  216. <div class="fieldWrapper">
  217. {{ field.errors }}
  218. {{ field.label_tag }}: {{ field }}
  219. </div>
  220. {% endfor %}
  221. <p><input type="submit" value="Send message" /></p>
  222. </form>
  223. Within this loop, ``{{ field }}`` is an instance of :class:`BoundField`.
  224. ``BoundField`` also has the following attributes, which can be useful in your
  225. templates:
  226. ``{{ field.label }}``
  227. The label of the field, e.g. ``E-mail address``.
  228. ``{{ field.label_tag }}``
  229. The field's label wrapped in the appropriate HTML ``<label>`` tag,
  230. e.g. ``<label for="id_email">E-mail address</label>``
  231. ``{{ field.html_name }}``
  232. The name of the field that will be used in the input element's name
  233. field. This takes the form prefix into account, if it has been set.
  234. ``{{ field.help_text }}``
  235. Any help text that has been associated with the field.
  236. ``{{ field.errors }}``
  237. Outputs a ``<ul class="errorlist">`` containing any validation errors
  238. corresponding to this field. You can customize the presentation of
  239. the errors with a ``{% for error in field.errors %}`` loop. In this
  240. case, each object in the loop is a simple string containing the error
  241. message.
  242. ``field.is_hidden``
  243. This attribute is ``True`` if the form field is a hidden field and
  244. ``False`` otherwise. It's not particularly useful as a template
  245. variable, but could be useful in conditional tests such as::
  246. {% if field.is_hidden %}
  247. {# Do something special #}
  248. {% endif %}
  249. Looping over hidden and visible fields
  250. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  251. If you're manually laying out a form in a template, as opposed to relying on
  252. Django's default form layout, you might want to treat ``<input type="hidden">``
  253. fields differently than non-hidden fields. For example, because hidden fields
  254. don't display anything, putting error messages "next to" the field could cause
  255. confusion for your users -- so errors for those fields should be handled
  256. differently.
  257. Django provides two methods on a form that allow you to loop over the hidden
  258. and visible fields independently: ``hidden_fields()`` and
  259. ``visible_fields()``. Here's a modification of an earlier example that uses
  260. these two methods::
  261. <form action="/contact/" method="post">
  262. {% for field in form.visible_fields %}
  263. <div class="fieldWrapper">
  264. {# Include the hidden fields in the form #}
  265. {% if forloop.first %}
  266. {% for hidden in form.hidden_fields %}
  267. {{ hidden }}
  268. {% endfor %}
  269. {% endif %}
  270. {{ field.errors }}
  271. {{ field.label_tag }}: {{ field }}
  272. </div>
  273. {% endfor %}
  274. <p><input type="submit" value="Send message" /></p>
  275. </form>
  276. This example does not handle any errors in the hidden fields. Usually, an
  277. error in a hidden field is a sign of form tampering, since normal form
  278. interaction won't alter them. However, you could easily insert some error
  279. displays for those form errors, as well.
  280. Reusable form templates
  281. -----------------------
  282. If your site uses the same rendering logic for forms in multiple places, you
  283. can reduce duplication by saving the form's loop in a standalone template and
  284. using the :ttag:`include` tag to reuse it in other templates::
  285. <form action="/contact/" method="post">
  286. {% include "form_snippet.html" %}
  287. <p><input type="submit" value="Send message" /></p>
  288. </form>
  289. # In form_snippet.html:
  290. {% for field in form %}
  291. <div class="fieldWrapper">
  292. {{ field.errors }}
  293. {{ field.label_tag }}: {{ field }}
  294. </div>
  295. {% endfor %}
  296. If the form object passed to a template has a different name within the
  297. context, you can alias it using the ``with`` argument of the :ttag:`include`
  298. tag::
  299. <form action="/comments/add/" method="post">
  300. {% include "form_snippet.html" with form=comment_form %}
  301. <p><input type="submit" value="Submit comment" /></p>
  302. </form>
  303. If you find yourself doing this often, you might consider creating a custom
  304. :ref:`inclusion tag<howto-custom-template-tags-inclusion-tags>`.
  305. Further topics
  306. ==============
  307. This covers the basics, but forms can do a whole lot more:
  308. .. toctree::
  309. :maxdepth: 2
  310. formsets
  311. modelforms
  312. media
  313. .. seealso::
  314. :doc:`The Forms Reference </ref/forms/index>`
  315. Covers the full API reference, including form fields, form widgets,
  316. and form and field validation.