index.txt 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. ``django.forms`` is Django's form-handling library.
  10. While it is possible to process form submissions just using Django's
  11. :class:`~django.http.HttpRequest` class, using the form library takes care of a
  12. number of common form-related tasks. Using it, you can:
  13. 1. Display an HTML form with automatically generated form widgets.
  14. 2. Checking submitted data against a set of validation rules.
  15. 3. Redisplaying a form in the case of validation errors.
  16. 4. Converting submitted form data to the relevant Python data types.
  17. Overview
  18. ========
  19. The library deals with these concepts:
  20. .. glossary::
  21. Widget
  22. A class that corresponds to an HTML form widget, e.g.
  23. ``<input type="text">`` or ``<textarea>``. This handles rendering of the
  24. widget as HTML.
  25. Field
  26. A class that is responsible for doing validation, e.g.
  27. an ``EmailField`` that makes sure its data is a valid e-mail address.
  28. Form
  29. A collection of fields that knows how to validate itself and
  30. display itself as HTML.
  31. Form Media
  32. The CSS and JavaScript resources that are required to render a form.
  33. The library is decoupled from the other Django components, such as the database
  34. layer, views and templates. It relies only on Django settings, a couple of
  35. ``django.utils`` helper functions and Django's internationalization hooks (but
  36. you're not required to be using internationalization features to use this
  37. library).
  38. Form objects
  39. ============
  40. A Form object encapsulates a sequence of form fields and a collection of
  41. validation rules that must be fulfilled in order for the form to be accepted.
  42. Form classes are created as subclasses of ``django.forms.Form`` and are
  43. make use of a declarative style that you'll be familiar with if you've used
  44. Django's database models.
  45. For example, consider a form used to implement "contact me" functionality on a
  46. personal Web site::
  47. from django import forms
  48. class ContactForm(forms.Form):
  49. subject = forms.CharField(max_length=100)
  50. message = forms.CharField()
  51. sender = forms.EmailField()
  52. cc_myself = forms.BooleanField(required=False)
  53. A form is composed of ``Field`` objects. In this case, our form has four
  54. fields: ``subject``, ``message``, ``sender`` and ``cc_myself``. ``CharField``,
  55. ``EmailField`` and ``BooleanField`` are just three of the available field types;
  56. a full list can be found in :ref:`ref-forms-fields`.
  57. If your form is going to be used to directly add or edit a Django model, you can
  58. use a :ref:`ModelForm <topics-forms-modelforms>` to avoid duplicating your model
  59. description.
  60. Using a form in a view
  61. ----------------------
  62. The standard pattern for processing a form in a view looks like this::
  63. def contact(request):
  64. if request.method == 'POST': # If the form has been submitted...
  65. form = ContactForm(request.POST) # A form bound to the POST data
  66. if form.is_valid(): # All validation rules pass
  67. # Process the data in form.cleaned_data
  68. # ...
  69. return HttpResponseRedirect('/thanks/') # Redirect after POST
  70. else:
  71. form = ContactForm() # An unbound form
  72. return render_to_response('contact.html', {
  73. 'form': form,
  74. })
  75. There are three code paths here:
  76. 1. If the form has not been submitted, an unbound instance of ContactForm is
  77. created and passed to the template.
  78. 2. If the form has been submitted, a bound instance of the form is created
  79. using ``request.POST``. If the submitted data is valid, it is processed
  80. and the user is re-directed to a "thanks" page.
  81. 3. If the form has been submitted but is invalid, the bound form instance is
  82. passed on to the template.
  83. .. versionchanged:: 1.0
  84. The ``cleaned_data`` attribute was called ``clean_data`` in earlier releases.
  85. The distinction between **bound** and **unbound** forms is important. An unbound
  86. form does not have any data associated with it; when rendered to the user, it
  87. will be empty or will contain default values. A bound form does have submitted
  88. data, and hence can be used to tell if that data is valid. If an invalid bound
  89. form is rendered it can include inline error messages telling the user where
  90. they went wrong.
  91. See :ref:`ref-forms-api-bound-unbound` for further information on the
  92. differences between bound and unbound forms.
  93. Processing the data from a form
  94. -------------------------------
  95. Once ``is_valid()`` returns ``True``, you can process the form submission safe
  96. in the knowledge that it conforms to the validation rules defined by your form.
  97. While you could access ``request.POST`` directly at this point, it is better to
  98. access ``form.cleaned_data``. This data has not only been validated but will
  99. also be converted in to the relevant Python types for you. In the above example,
  100. ``cc_myself`` will be a boolean value. Likewise, fields such as ``IntegerField``
  101. and ``FloatField`` convert values to a Python int and float respectively.
  102. Extending the above example, here's how the form data could be processed::
  103. if form.is_valid():
  104. subject = form.cleaned_data['subject']
  105. message = form.cleaned_data['message']
  106. sender = form.cleaned_data['sender']
  107. cc_myself = form.cleaned_data['cc_myself']
  108. recipients = ['info@example.com']
  109. if cc_myself:
  110. recipients.append(sender)
  111. from django.core.mail import send_mail
  112. send_mail(subject, message, sender, recipients)
  113. return HttpResponseRedirect('/thanks/') # Redirect after POST
  114. For more on sending e-mail from Django, see :ref:`topics-email`.
  115. Displaying a form using a template
  116. ----------------------------------
  117. Forms are designed to work with the Django template language. In the above
  118. example, we passed our ``ContactForm`` instance to the template using the
  119. context variable ``form``. Here's a simple example template::
  120. <form action="/contact/" method="POST">
  121. {{ form.as_p }}
  122. <input type="submit" value="Submit">
  123. </form>
  124. The form only outputs its own fields; it is up to you to provide the surrounding
  125. ``<form>`` tags and the submit button.
  126. ``form.as_p`` will output the form with each form field and accompanying label
  127. wrapped in a paragraph. Here's the output for our example template::
  128. <form action="/contact/" method="POST">
  129. <p><label for="id_subject">Subject:</label>
  130. <input id="id_subject" type="text" name="subject" maxlength="100" /></p>
  131. <p><label for="id_message">Message:</label>
  132. <input type="text" name="message" id="id_message" /></p>
  133. <p><label for="id_sender">Sender:</label>
  134. <input type="text" name="sender" id="id_sender" /></p>
  135. <p><label for="id_cc_myself">Cc myself:</label>
  136. <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>
  137. <input type="submit" value="Submit">
  138. </form>
  139. Note that each form field has an ID attribute set to ``id_<field-name>``, which
  140. is referenced by the accompanying label tag. This is important for ensuring
  141. forms are accessible to assistive technology such as screen reader software. You
  142. can also :ref:`customize the way in which labels and ids are generated
  143. <ref-forms-api-configuring-label>`.
  144. You can also use ``form.as_table`` to output table rows (you'll need to provide
  145. your own ``<table>`` tags) and ``form.as_li`` to output list items.
  146. Customizing the form template
  147. -----------------------------
  148. If the default generated HTML is not to your taste, you can completely customize
  149. the way a form is presented using the Django template language. Extending the
  150. above example::
  151. <form action="/contact/" method="POST">
  152. <div class="fieldWrapper">
  153. {{ form.subject.errors }}
  154. <label for="id_subject">E-mail subject:</label>
  155. {{ form.subject }}
  156. </div>
  157. <div class="fieldWrapper">
  158. {{ form.message.errors }}
  159. <label for="id_message">Your message:</label>
  160. {{ form.message }}
  161. </div>
  162. <div class="fieldWrapper">
  163. {{ form.sender.errors }}
  164. <label for="id_sender">Your email address:</label>
  165. {{ form.sender }}
  166. </div>
  167. <div class="fieldWrapper">
  168. {{ form.cc_myself.errors }}
  169. <label for="id_cc_myself">CC yourself?</label>
  170. {{ form.cc_myself }}
  171. </div>
  172. <p><input type="submit" value="Send message"></p>
  173. </form>
  174. Each named form-field can be output to the template using
  175. ``{{ form.name_of_field }}``, which will produce the HTML needed to display the
  176. form widget. Using ``{{ form.name_of_field.errors }}`` displays a list of form
  177. errors, rendered as an unordered list. This might look like::
  178. <ul class="errorlist">
  179. <li>Sender is required.</li>
  180. </ul>
  181. The list has a CSS class of ``errorlist`` to allow you to style its appearance.
  182. If you wish to further customize the display of errors you can do so by looping
  183. over them::
  184. {% if form.subject.errors %}
  185. <ol>
  186. {% for error in form.message.errors %}
  187. <li><strong>{{ error|escape }}</strong></li>
  188. {% endfor %}
  189. </ol>
  190. {% endif %}
  191. Further topics
  192. ==============
  193. This covers the basics, but forms can do a whole lot more:
  194. .. toctree::
  195. :maxdepth: 1
  196. modelforms
  197. formsets
  198. media
  199. .. seealso::
  200. The :ref:`form API reference <ref-forms-index>`.