parts/django/docs/topics/forms/index.txt
changeset 307 c6bca38c1cbf
equal deleted inserted replaced
306:5ff1fc726848 307:c6bca38c1cbf
       
     1 ==================
       
     2 Working with forms
       
     3 ==================
       
     4 
       
     5 .. admonition:: About this document
       
     6 
       
     7     This document provides an introduction to Django's form handling features.
       
     8     For a more detailed look at specific areas of the forms API, see
       
     9     :doc:`/ref/forms/api`, :doc:`/ref/forms/fields`, and
       
    10     :doc:`/ref/forms/validation`.
       
    11 
       
    12 .. highlightlang:: html+django
       
    13 
       
    14 ``django.forms`` is Django's form-handling library.
       
    15 
       
    16 While it is possible to process form submissions just using Django's
       
    17 :class:`~django.http.HttpRequest` class, using the form library takes care of a
       
    18 number of common form-related tasks. Using it, you can:
       
    19 
       
    20     1. Display an HTML form with automatically generated form widgets.
       
    21     2. Check submitted data against a set of validation rules.
       
    22     3. Redisplay a form in the case of validation errors.
       
    23     4. Convert submitted form data to the relevant Python data types.
       
    24 
       
    25 Overview
       
    26 ========
       
    27 
       
    28 The library deals with these concepts:
       
    29 
       
    30 .. glossary::
       
    31 
       
    32     Widget
       
    33         A class that corresponds to an HTML form widget, e.g.
       
    34         ``<input type="text">`` or ``<textarea>``. This handles rendering of the
       
    35         widget as HTML.
       
    36 
       
    37     Field
       
    38         A class that is responsible for doing validation, e.g.
       
    39         an ``EmailField`` that makes sure its data is a valid e-mail address.
       
    40 
       
    41     Form
       
    42         A collection of fields that knows how to validate itself and
       
    43         display itself as HTML.
       
    44 
       
    45     Form Media
       
    46         The CSS and JavaScript resources that are required to render a form.
       
    47 
       
    48 The library is decoupled from the other Django components, such as the database
       
    49 layer, views and templates. It relies only on Django settings, a couple of
       
    50 ``django.utils`` helper functions and Django's internationalization hooks (but
       
    51 you're not required to be using internationalization features to use this
       
    52 library).
       
    53 
       
    54 Form objects
       
    55 ============
       
    56 
       
    57 A Form object encapsulates a sequence of form fields and a collection of
       
    58 validation rules that must be fulfilled in order for the form to be accepted.
       
    59 Form classes are created as subclasses of ``django.forms.Form`` and
       
    60 make use of a declarative style that you'll be familiar with if you've used
       
    61 Django's database models.
       
    62 
       
    63 For example, consider a form used to implement "contact me" functionality on a
       
    64 personal Web site:
       
    65 
       
    66 .. code-block:: python
       
    67 
       
    68     from django import forms
       
    69 
       
    70     class ContactForm(forms.Form):
       
    71         subject = forms.CharField(max_length=100)
       
    72         message = forms.CharField()
       
    73         sender = forms.EmailField()
       
    74         cc_myself = forms.BooleanField(required=False)
       
    75 
       
    76 A form is composed of ``Field`` objects. In this case, our form has four
       
    77 fields: ``subject``, ``message``, ``sender`` and ``cc_myself``. ``CharField``,
       
    78 ``EmailField`` and ``BooleanField`` are just three of the available field types;
       
    79 a full list can be found in :doc:`/ref/forms/fields`.
       
    80 
       
    81 If your form is going to be used to directly add or edit a Django model, you can
       
    82 use a :doc:`ModelForm </topics/forms/modelforms>` to avoid duplicating your model
       
    83 description.
       
    84 
       
    85 Using a form in a view
       
    86 ----------------------
       
    87 
       
    88 The standard pattern for processing a form in a view looks like this:
       
    89 
       
    90 .. code-block:: python
       
    91 
       
    92    def contact(request):
       
    93        if request.method == 'POST': # If the form has been submitted...
       
    94            form = ContactForm(request.POST) # A form bound to the POST data
       
    95            if form.is_valid(): # All validation rules pass
       
    96                # Process the data in form.cleaned_data
       
    97                # ...
       
    98                return HttpResponseRedirect('/thanks/') # Redirect after POST
       
    99        else:
       
   100            form = ContactForm() # An unbound form
       
   101 
       
   102        return render_to_response('contact.html', {
       
   103            'form': form,
       
   104        })
       
   105 
       
   106 
       
   107 There are three code paths here:
       
   108 
       
   109     1. If the form has not been submitted, an unbound instance of ContactForm is
       
   110        created and passed to the template.
       
   111     2. If the form has been submitted, a bound instance of the form is created
       
   112        using ``request.POST``. If the submitted data is valid, it is processed
       
   113        and the user is re-directed to a "thanks" page.
       
   114     3. If the form has been submitted but is invalid, the bound form instance is
       
   115        passed on to the template.
       
   116 
       
   117 .. versionchanged:: 1.0
       
   118     The ``cleaned_data`` attribute was called ``clean_data`` in earlier releases.
       
   119 
       
   120 The distinction between **bound** and **unbound** forms is important. An unbound
       
   121 form does not have any data associated with it; when rendered to the user, it
       
   122 will be empty or will contain default values. A bound form does have submitted
       
   123 data, and hence can be used to tell if that data is valid. If an invalid bound
       
   124 form is rendered it can include inline error messages telling the user where
       
   125 they went wrong.
       
   126 
       
   127 See :ref:`ref-forms-api-bound-unbound` for further information on the
       
   128 differences between bound and unbound forms.
       
   129 
       
   130 Handling file uploads with a form
       
   131 ---------------------------------
       
   132 
       
   133 To see how to handle file uploads with your form see
       
   134 :ref:`binding-uploaded-files` for more information.
       
   135 
       
   136 Processing the data from a form
       
   137 -------------------------------
       
   138 
       
   139 Once ``is_valid()`` returns ``True``, you can process the form submission safe
       
   140 in the knowledge that it conforms to the validation rules defined by your form.
       
   141 While you could access ``request.POST`` directly at this point, it is better to
       
   142 access ``form.cleaned_data``. This data has not only been validated but will
       
   143 also be converted in to the relevant Python types for you. In the above example,
       
   144 ``cc_myself`` will be a boolean value. Likewise, fields such as ``IntegerField``
       
   145 and ``FloatField`` convert values to a Python int and float respectively.
       
   146 
       
   147 Extending the above example, here's how the form data could be processed:
       
   148 
       
   149 .. code-block:: python
       
   150 
       
   151     if form.is_valid():
       
   152         subject = form.cleaned_data['subject']
       
   153         message = form.cleaned_data['message']
       
   154         sender = form.cleaned_data['sender']
       
   155         cc_myself = form.cleaned_data['cc_myself']
       
   156 
       
   157         recipients = ['info@example.com']
       
   158         if cc_myself:
       
   159             recipients.append(sender)
       
   160 
       
   161         from django.core.mail import send_mail
       
   162         send_mail(subject, message, sender, recipients)
       
   163         return HttpResponseRedirect('/thanks/') # Redirect after POST
       
   164 
       
   165 For more on sending e-mail from Django, see :doc:`/topics/email`.
       
   166 
       
   167 Displaying a form using a template
       
   168 ----------------------------------
       
   169 
       
   170 Forms are designed to work with the Django template language. In the above
       
   171 example, we passed our ``ContactForm`` instance to the template using the
       
   172 context variable ``form``. Here's a simple example template::
       
   173 
       
   174     <form action="/contact/" method="post">
       
   175     {{ form.as_p }}
       
   176     <input type="submit" value="Submit" />
       
   177     </form>
       
   178 
       
   179 The form only outputs its own fields; it is up to you to provide the surrounding
       
   180 ``<form>`` tags and the submit button.
       
   181 
       
   182 ``form.as_p`` will output the form with each form field and accompanying label
       
   183 wrapped in a paragraph. Here's the output for our example template::
       
   184 
       
   185    <form action="/contact/" method="post">
       
   186    <p><label for="id_subject">Subject:</label>
       
   187        <input id="id_subject" type="text" name="subject" maxlength="100" /></p>
       
   188    <p><label for="id_message">Message:</label>
       
   189        <input type="text" name="message" id="id_message" /></p>
       
   190    <p><label for="id_sender">Sender:</label>
       
   191        <input type="text" name="sender" id="id_sender" /></p>
       
   192    <p><label for="id_cc_myself">Cc myself:</label>
       
   193        <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>
       
   194    <input type="submit" value="Submit" />
       
   195    </form>
       
   196 
       
   197 Note that each form field has an ID attribute set to ``id_<field-name>``, which
       
   198 is referenced by the accompanying label tag. This is important for ensuring
       
   199 forms are accessible to assistive technology such as screen reader software. You
       
   200 can also :ref:`customize the way in which labels and ids are generated
       
   201 <ref-forms-api-configuring-label>`.
       
   202 
       
   203 You can also use ``form.as_table`` to output table rows (you'll need to provide
       
   204 your own ``<table>`` tags) and ``form.as_ul`` to output list items.
       
   205 
       
   206 Customizing the form template
       
   207 -----------------------------
       
   208 
       
   209 If the default generated HTML is not to your taste, you can completely customize
       
   210 the way a form is presented using the Django template language. Extending the
       
   211 above example::
       
   212 
       
   213     <form action="/contact/" method="post">
       
   214         {{ form.non_field_errors }}
       
   215         <div class="fieldWrapper">
       
   216             {{ form.subject.errors }}
       
   217             <label for="id_subject">E-mail subject:</label>
       
   218             {{ form.subject }}
       
   219         </div>
       
   220         <div class="fieldWrapper">
       
   221             {{ form.message.errors }}
       
   222             <label for="id_message">Your message:</label>
       
   223             {{ form.message }}
       
   224         </div>
       
   225         <div class="fieldWrapper">
       
   226             {{ form.sender.errors }}
       
   227             <label for="id_sender">Your email address:</label>
       
   228             {{ form.sender }}
       
   229         </div>
       
   230         <div class="fieldWrapper">
       
   231             {{ form.cc_myself.errors }}
       
   232             <label for="id_cc_myself">CC yourself?</label>
       
   233             {{ form.cc_myself }}
       
   234         </div>
       
   235         <p><input type="submit" value="Send message" /></p>
       
   236     </form>
       
   237 
       
   238 Each named form-field can be output to the template using
       
   239 ``{{ form.name_of_field }}``, which will produce the HTML needed to display the
       
   240 form widget. Using ``{{ form.name_of_field.errors }}`` displays a list of form
       
   241 errors, rendered as an unordered list. This might look like::
       
   242 
       
   243    <ul class="errorlist">
       
   244        <li>Sender is required.</li>
       
   245    </ul>
       
   246 
       
   247 The list has a CSS class of ``errorlist`` to allow you to style its appearance.
       
   248 If you wish to further customize the display of errors you can do so by looping
       
   249 over them::
       
   250 
       
   251     {% if form.subject.errors %}
       
   252         <ol>
       
   253         {% for error in form.subject.errors %}
       
   254             <li><strong>{{ error|escape }}</strong></li>
       
   255         {% endfor %}
       
   256         </ol>
       
   257     {% endif %}
       
   258 
       
   259 Looping over the form's fields
       
   260 ------------------------------
       
   261 
       
   262 If you're using the same HTML for each of your form fields, you can reduce
       
   263 duplicate code by looping through each field in turn using a ``{% for %}``
       
   264 loop::
       
   265 
       
   266     <form action="/contact/" method="post">
       
   267         {% for field in form %}
       
   268             <div class="fieldWrapper">
       
   269                 {{ field.errors }}
       
   270                 {{ field.label_tag }}: {{ field }}
       
   271             </div>
       
   272         {% endfor %}
       
   273         <p><input type="submit" value="Send message" /></p>
       
   274     </form>
       
   275 
       
   276 Within this loop, ``{{ field }}`` is an instance of :class:`BoundField`.
       
   277 ``BoundField`` also has the following attributes, which can be useful in your
       
   278 templates:
       
   279 
       
   280     ``{{ field.label }}``
       
   281         The label of the field, e.g. ``E-mail address``.
       
   282 
       
   283     ``{{ field.label_tag }}``
       
   284         The field's label wrapped in the appropriate HTML ``<label>`` tag,
       
   285         e.g. ``<label for="id_email">E-mail address</label>``
       
   286 
       
   287     ``{{ field.html_name }}``
       
   288         The name of the field that will be used in the input element's name
       
   289         field. This takes the form prefix into account, if it has been set.
       
   290 
       
   291     ``{{ field.help_text }}``
       
   292         Any help text that has been associated with the field.
       
   293 
       
   294     ``{{ field.errors }}``
       
   295         Outputs a ``<ul class="errorlist">`` containing any validation errors
       
   296         corresponding to this field. You can customize the presentation of
       
   297         the errors with a ``{% for error in field.errors %}`` loop. In this
       
   298         case, each object in the loop is a simple string containing the error
       
   299         message.
       
   300 
       
   301     ``field.is_hidden``
       
   302         This attribute is ``True`` if the form field is a hidden field and
       
   303         ``False`` otherwise. It's not particularly useful as a template
       
   304         variable, but could be useful in conditional tests such as::
       
   305 
       
   306             {% if field.is_hidden %}
       
   307                {# Do something special #}
       
   308             {% endif %}
       
   309 
       
   310 Looping over hidden and visible fields
       
   311 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   312 
       
   313 If you're manually laying out a form in a template, as opposed to relying on
       
   314 Django's default form layout, you might want to treat ``<input type="hidden">``
       
   315 fields differently than non-hidden fields. For example, because hidden fields
       
   316 don't display anything, putting error messages "next to" the field could cause
       
   317 confusion for your users -- so errors for those fields should be handled
       
   318 differently.
       
   319 
       
   320 Django provides two methods on a form that allow you to loop over the hidden
       
   321 and visible fields independently: ``hidden_fields()`` and
       
   322 ``visible_fields()``. Here's a modification of an earlier example that uses
       
   323 these two methods::
       
   324 
       
   325     <form action="/contact/" method="post">
       
   326         {% for field in form.visible_fields %}
       
   327             <div class="fieldWrapper">
       
   328 
       
   329                 {# Include the hidden fields in the form #}
       
   330                 {% if forloop.first %}
       
   331                     {% for hidden in form.hidden_fields %}
       
   332                     {{ hidden }}
       
   333                     {% endfor %}
       
   334                 {% endif %}
       
   335 
       
   336                 {{ field.errors }}
       
   337                 {{ field.label_tag }}: {{ field }}
       
   338             </div>
       
   339         {% endfor %}
       
   340         <p><input type="submit" value="Send message" /></p>
       
   341     </form>
       
   342 
       
   343 This example does not handle any errors in the hidden fields. Usually, an
       
   344 error in a hidden field is a sign of form tampering, since normal form
       
   345 interaction won't alter them. However, you could easily insert some error
       
   346 displays for those form errors, as well.
       
   347 
       
   348 .. versionadded:: 1.1
       
   349     The ``hidden_fields`` and ``visible_fields`` methods are new in Django
       
   350     1.1.
       
   351 
       
   352 Reusable form templates
       
   353 -----------------------
       
   354 
       
   355 If your site uses the same rendering logic for forms in multiple places, you
       
   356 can reduce duplication by saving the form's loop in a standalone template and
       
   357 using the :ttag:`include` tag to reuse it in other templates::
       
   358 
       
   359     <form action="/contact/" method="post">
       
   360         {% include "form_snippet.html" %}
       
   361         <p><input type="submit" value="Send message" /></p>
       
   362     </form>
       
   363 
       
   364     # In form_snippet.html:
       
   365 
       
   366     {% for field in form %}
       
   367         <div class="fieldWrapper">
       
   368             {{ field.errors }}
       
   369             {{ field.label_tag }}: {{ field }}
       
   370         </div>
       
   371     {% endfor %}
       
   372 
       
   373 If the form object passed to a template has a different name within the
       
   374 context, you can alias it using the :ttag:`with` tag::
       
   375 
       
   376     <form action="/comments/add/" method="post">
       
   377         {% with comment_form as form %}
       
   378             {% include "form_snippet.html" %}
       
   379         {% endwith %}
       
   380         <p><input type="submit" value="Submit comment" /></p>
       
   381     </form>
       
   382 
       
   383 If you find yourself doing this often, you might consider creating a custom
       
   384 :ref:`inclusion tag<howto-custom-template-tags-inclusion-tags>`.
       
   385 
       
   386 Further topics
       
   387 ==============
       
   388 
       
   389 This covers the basics, but forms can do a whole lot more:
       
   390 
       
   391 .. toctree::
       
   392    :maxdepth: 2
       
   393 
       
   394    modelforms
       
   395    formsets
       
   396    media
       
   397 
       
   398 .. seealso::
       
   399 
       
   400     :doc:`The Forms Reference </ref/forms/index>`
       
   401         Covers the full API reference, including form fields, form widgets, 
       
   402         and form and field validation.