Django

Code

root/django/branches/gis/docs/forms.txt

Revision 8215, 107.0 kB (checked in by jbronn, 4 months ago)

gis: Merged revisions 7981-8001,8003-8011,8013-8033,8035-8036,8038-8039,8041-8063,8065-8076,8078-8139,8141-8154,8156-8214 via svnmerge from trunk.

  • Property svn:eol-style set to native
Line 
1 =================
2 The forms library
3 =================
4
5 ``django.forms`` is Django's form-handling library.
6
7 .. admonition:: Looking for oldforms?
8
9     ``django.forms`` was once called ``newforms`` since it replaced Django's
10     original form/manipulator/validation framework. The old form handling
11     library is still available as `django.oldforms`_, but will be removed
12     in a future version of Django.
13
14 .. _django.oldforms: ../oldforms/
15
16 Overview
17 ========
18
19 ``django.forms`` is intended to handle HTML form display, data processing
20 (validation) and redisplay. It's what you use if you want to perform
21 server-side validation for an HTML form.
22
23 For example, if your Web site has a contact form that visitors can use to
24 send you e-mail, you'd use this library to implement the display of the HTML
25 form fields, along with the form validation. Any time you need to use an HTML
26 ``<form>``, you can use this library.
27
28 The library deals with these concepts:
29
30     * **Widget** -- A class that corresponds to an HTML form widget, e.g.
31       ``<input type="text">`` or ``<textarea>``. This handles rendering of the
32       widget as HTML.
33
34     * **Field** -- A class that is responsible for doing validation, e.g.
35       an ``EmailField`` that makes sure its data is a valid e-mail address.
36
37     * **Form** -- A collection of fields that knows how to validate itself and
38       display itself as HTML.
39
40     * **Media** -- A definition of the CSS and JavaScript resources that are
41       required to render a form.
42
43 The library is decoupled from the other Django components, such as the database
44 layer, views and templates. It relies only on Django settings, a couple of
45 ``django.utils`` helper functions and Django's internationalization hooks (but
46 you're not required to be using internationalization features to use this
47 library).
48
49 Form objects
50 ============
51
52 The primary way of using the ``forms`` library is to create a form object.
53 Do this by subclassing ``django.forms.Form`` and specifying the form's
54 fields, in a declarative style that you'll be familiar with if you've used
55 Django database models. In this section, we'll iteratively develop a form
56 object that you might use to implement "contact me" functionality on your
57 personal Web site.
58
59 Start with this basic ``Form`` subclass, which we'll call ``ContactForm``::
60
61     from django import forms
62
63     class ContactForm(forms.Form):
64         subject = forms.CharField(max_length=100)
65         message = forms.CharField()
66         sender = forms.EmailField()
67         cc_myself = forms.BooleanField(required=False)
68
69 A form is composed of ``Field`` objects. In this case, our form has four
70 fields: ``subject``, ``message``, ``sender`` and ``cc_myself``. We'll explain
71 the different types of fields -- e.g., ``CharField`` and ``EmailField`` --
72 shortly.
73
74 Creating ``Form`` instances
75 ---------------------------
76
77 A ``Form`` instance is either **bound** to a set of data, or **unbound**.
78
79     * If it's **bound** to a set of data, it's capable of validating that data
80       and rendering the form as HTML with the data displayed in the HTML.
81
82     * If it's **unbound**, it cannot do validation (because there's no data to
83       validate!), but it can still render the blank form as HTML.
84
85 To create an unbound ``Form`` instance, simply instantiate the class::
86
87     >>> f = ContactForm()
88
89 To bind data to a form, pass the data as a dictionary as the first parameter to
90 your ``Form`` class constructor::
91
92     >>> data = {'subject': 'hello',
93     ...         'message': 'Hi there',
94     ...         'sender': 'foo@example.com',
95     ...         'cc_myself': True}
96     >>> f = ContactForm(data)
97
98 In this dictionary, the keys are the field names, which correspond to the
99 attributes in your ``Form`` class. The values are the data you're trying
100 to validate. These will usually be strings, but there's no requirement that
101 they be strings; the type of data you pass depends on the ``Field``, as we'll
102 see in a moment.
103
104 If you need to distinguish between bound and unbound form instances at runtime,
105 check the value of the form's ``is_bound`` attribute::
106
107     >>> f = ContactForm()
108     >>> f.is_bound
109     False
110     >>> f = ContactForm({'subject': 'hello'})
111     >>> f.is_bound
112     True
113
114 Note that passing an empty dictionary creates a *bound* form with empty data::
115
116     >>> f = ContactForm({})
117     >>> f.is_bound
118     True
119
120 If you have a bound ``Form`` instance and want to change the data somehow, or
121 if you want to bind an unbound ``Form`` instance to some data, create another
122 ``Form`` instance. There is no way to change data in a ``Form`` instance. Once
123 a ``Form`` instance has been created, you should consider its data immutable,
124 whether it has data or not.
125
126 Using forms to validate data
127 ----------------------------
128
129 The primary task of a ``Form`` object is to validate data. With a bound
130 ``Form`` instance, call the ``is_valid()`` method to run validation and return
131 a boolean designating whether the data was valid::
132
133     >>> data = {'subject': 'hello',
134     ...         'message': 'Hi there',
135     ...         'sender': 'foo@example.com',
136     ...         'cc_myself': True}
137     >>> f = ContactForm(data)
138     >>> f.is_valid()
139     True
140
141 Let's try with some invalid data. In this case, ``subject`` is blank (an error,
142 because all fields are required by default) and ``sender`` is not a valid
143 e-mail address::
144
145     >>> data = {'subject': '',
146     ...         'message': 'Hi there',
147     ...         'sender': 'invalid e-mail address',
148     ...         'cc_myself': True}
149     >>> f = ContactForm(data)
150     >>> f.is_valid()
151     False
152
153 Access the ``errors`` attribute to get a dictionary of error messages::
154
155     >>> f.errors
156     {'sender': [u'Enter a valid e-mail address.'], 'subject': [u'This field is required.']}
157
158 In this dictionary, the keys are the field names, and the values are lists of
159 Unicode strings representing the error messages. The error messages are stored
160 in lists because a field can have multiple error messages.
161
162 You can access ``errors`` without having to call ``is_valid()`` first. The
163 form's data will be validated the first time either you call ``is_valid()`` or
164 access ``errors``.
165
166 The validation routines will only get called once, regardless of how many times
167 you access ``errors`` or call ``is_valid()``. This means that if validation has
168 side effects, those side effects will only be triggered once.
169
170 Behavior of unbound forms
171 ~~~~~~~~~~~~~~~~~~~~~~~~~
172
173 It's meaningless to validate a form with no data, but, for the record, here's
174 what happens with unbound forms::
175
176     >>> f = ContactForm()
177     >>> f.is_valid()
178     False
179     >>> f.errors
180     {}
181
182 Accessing "clean" data
183 ----------------------
184
185 Each ``Field`` in a ``Form`` class is responsible not only for validating data,
186 but also for "cleaning" it -- normalizing it to a consistent format. This is a
187 nice feature, because it allows data for a particular field to be input in
188 a variety of ways, always resulting in consistent output.
189
190 For example, ``DateField`` normalizes input into a Python ``datetime.date``
191 object. Regardless of whether you pass it a string in the format
192 ``'1994-07-15'``, a ``datetime.date`` object or a number of other formats,
193 ``DateField`` will always normalize it to a ``datetime.date`` object as long as
194 it's valid.
195
196 Once you've created a ``Form`` instance with a set of data and validated it,
197 you can access the clean data via the ``cleaned_data`` attribute of the ``Form``
198 object::
199
200     >>> data = {'subject': 'hello',
201     ...         'message': 'Hi there',
202     ...         'sender': 'foo@example.com',
203     ...         'cc_myself': True}
204     >>> f = ContactForm(data)
205     >>> f.is_valid()
206     True
207     >>> f.cleaned_data
208     {'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'}
209
210 .. note::
211     **New in Django development version** The ``cleaned_data`` attribute was
212     called ``clean_data`` in earlier releases.
213
214 Note that any text-based field -- such as ``CharField`` or ``EmailField`` --
215 always cleans the input into a Unicode string. We'll cover the encoding
216 implications later in this document.
217
218 If your data does *not* validate, your ``Form`` instance will not have a
219 ``cleaned_data`` attribute::
220
221     >>> data = {'subject': '',
222     ...         'message': 'Hi there',
223     ...         'sender': 'invalid e-mail address',
224     ...         'cc_myself': True}
225     >>> f = ContactForm(data)
226     >>> f.is_valid()
227     False
228     >>> f.cleaned_data
229     Traceback (most recent call last):
230     ...
231     AttributeError: 'ContactForm' object has no attribute 'cleaned_data'
232
233 ``cleaned_data`` will always *only* contain a key for fields defined in the
234 ``Form``, even if you pass extra data when you define the ``Form``. In this
235 example, we pass a bunch of extra fields to the ``ContactForm`` constructor,
236 but ``cleaned_data`` contains only the form's fields::
237
238     >>> data = {'subject': 'hello',
239     ...         'message': 'Hi there',
240     ...         'sender': 'foo@example.com',
241     ...         'cc_myself': True,
242     ...         'extra_field_1': 'foo',
243     ...         'extra_field_2': 'bar',
244     ...         'extra_field_3': 'baz'}
245     >>> f = ContactForm(data)
246     >>> f.is_valid()
247     True
248     >>> f.cleaned_data # Doesn't contain extra_field_1, etc.
249     {'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'}
250
251 ``cleaned_data`` will include a key and value for *all* fields defined in the
252 ``Form``, even if the data didn't include a value for fields that are not
253 required. In this example, the data dictionary doesn't include a value for the
254 ``nick_name`` field, but ``cleaned_data`` includes it, with an empty value::
255
256     >>> class OptionalPersonForm(Form):
257     ...     first_name = CharField()
258     ...     last_name = CharField()
259     ...     nick_name = CharField(required=False)
260     >>> data = {'first_name': u'John', 'last_name': u'Lennon'}
261     >>> f = OptionalPersonForm(data)
262     >>> f.is_valid()
263     True
264     >>> f.cleaned_data
265     {'nick_name': u'', 'first_name': u'John', 'last_name': u'Lennon'}
266
267 In this above example, the ``cleaned_data`` value for ``nick_name`` is set to an
268 empty string, because ``nick_name`` is ``CharField``, and ``CharField``\s treat
269 empty values as an empty string. Each field type knows what its "blank" value
270 is -- e.g., for ``DateField``, it's ``None`` instead of the empty string. For
271 full details on each field's behavior in this case, see the "Empty value" note
272 for each field in the "Built-in ``Field`` classes" section below.
273
274 You can write code to perform validation for particular form fields (based on
275 their name) or for the form as a whole (considering combinations of various
276 fields). More information about this is in the `Custom form and field
277 validation`_ section, below.
278
279 Behavior of unbound forms
280 ~~~~~~~~~~~~~~~~~~~~~~~~~
281
282 It's meaningless to request "cleaned" data in a form with no data, but, for the
283 record, here's what happens with unbound forms::
284
285     >>> f = ContactForm()
286     >>> f.cleaned_data
287     Traceback (most recent call last):
288     ...
289     AttributeError: 'ContactForm' object has no attribute 'cleaned_data'
290
291 Outputting forms as HTML
292 ------------------------
293
294 The second task of a ``Form`` object is to render itself as HTML. To do so,
295 simply ``print`` it::
296
297     >>> f = ContactForm()
298     >>> print f
299     <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
300     <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
301     <tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr>
302     <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>
303
304 If the form is bound to data, the HTML output will include that data
305 appropriately. For example, if a field is represented by an
306 ``<input type="text">``, the data will be in the ``value`` attribute. If a
307 field is represented by an ``<input type="checkbox">``, then that HTML will
308 include ``checked="checked"`` if appropriate::
309
310     >>> data = {'subject': 'hello',
311     ...         'message': 'Hi there',
312     ...         'sender': 'foo@example.com',
313     ...         'cc_myself': True}
314     >>> f = ContactForm(data)
315     >>> print f
316     <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" value="hello" /></td></tr>
317     <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" value="Hi there" /></td></tr>
318     <tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" value="foo@example.com" /></td></tr>
319     <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" checked="checked" /></td></tr>
320
321 This default output is a two-column HTML table, with a ``<tr>`` for each field.
322 Notice the following:
323
324     * For flexibility, the output does *not* include the ``<table>`` and
325       ``</table>`` tags, nor does it include the ``<form>`` and ``</form>``
326       tags or an ``<input type="submit">`` tag. It's your job to do that.
327
328     * Each field type has a default HTML representation. ``CharField`` and
329       ``EmailField`` are represented by an ``<input type="text">``.
330       ``BooleanField`` is represented by an ``<input type="checkbox">``. Note
331       these are merely sensible defaults; you can specify which HTML to use for
332       a given field by using widgets, which we'll explain shortly.
333
334     * The HTML ``name`` for each tag is taken directly from its attribute name
335       in the ``ContactForm`` class.
336
337     * The text label for each field -- e.g. ``'Subject:'``, ``'Message:'`` and
338       ``'Cc myself:'`` is generated from the field name by converting all
339       underscores to spaces and upper-casing the first letter. Again, note
340       these are merely sensible defaults; you can also specify labels manually.
341
342     * Each text label is surrounded in an HTML ``<label>`` tag, which points
343       to the appropriate form field via its ``id``. Its ``id``, in turn, is
344       generated by prepending ``'id_'`` to the field name. The ``id``
345       attributes and ``<label>`` tags are included in the output by default, to
346       follow best practices, but you can change that behavior.
347
348 Although ``<table>`` output is the default output style when you ``print`` a
349 form, other output styles are available. Each style is available as a method on
350 a form object, and each rendering method returns a Unicode object.
351
352 ``as_p()``
353 ~~~~~~~~~~
354
355 ``Form.as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>``
356 containing one field::
357
358     >>> f = ContactForm()
359     >>> f.as_p()
360     u'<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>\n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>\n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p>\n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>'
361     >>> print f.as_p()
362     <p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>
363     <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>
364     <p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p>
365     <p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>
366
367 ``as_ul()``
368 ~~~~~~~~~~~
369
370 ``Form.as_ul()`` renders the form as a series of ``<li>`` tags, with each
371 ``<li>`` containing one field. It does *not* include the ``<ul>`` or ``</ul>``,
372 so that you can specify any HTML attributes on the ``<ul>`` for flexibility::
373
374     >>> f = ContactForm()
375     >>> f.as_ul()
376     u'<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>\n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>\n<li><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></li>\n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>'
377     >>> print f.as_ul()
378     <li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>
379     <li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>
380     <li><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></li>
381     <li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>
382
383 ``as_table()``
384 ~~~~~~~~~~~~~~
385
386 Finally, ``Form.as_table()`` outputs the form as an HTML ``<table>``. This is
387 exactly the same as ``print``. In fact, when you ``print`` a form object, it
388 calls its ``as_table()`` method behind the scenes::
389
390     >>> f = ContactForm()
391     >>> f.as_table()
392     u'<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>\n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr>\n<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>'
393     >>> print f.as_table()
394     <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
395     <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
396     <tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr>
397     <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>
398
399 Configuring HTML ``<label>`` tags
400 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
401
402 An HTML ``<label>`` tag designates which label text is associated with which
403 form element. This small enhancement makes forms more usable and more accessible
404 to assistive devices. It's always a good idea to use ``<label>`` tags.
405
406 By default, the form rendering methods include HTML ``id`` attributes on the
407 form elements and corresponding ``<label>`` tags around the labels. The ``id``
408 attribute values are generated by prepending ``id_`` to the form field names.
409 This behavior is configurable, though, if you want to change the ``id``
410 convention or remove HTML ``id`` attributes and ``<label>`` tags entirely.
411
412 Use the ``auto_id`` argument to the ``Form`` constructor to control the label
413 and ``id`` behavior. This argument must be ``True``, ``False`` or a string.
414
415 If ``auto_id`` is ``False``, then the form output will not include ``<label>``
416 tags nor ``id`` attributes::
417
418     >>> f = ContactForm(auto_id=False)
419     >>> print f.as_table()
420     <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /></td></tr>
421     <tr><th>Message:</th><td><input type="text" name="message" /></td></tr>
422     <tr><th>Sender:</th><td><input type="text" name="sender" /></td></tr>
423     <tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr>
424     >>> print f.as_ul()
425     <li>Subject: <input type="text" name="subject" maxlength="100" /></li>
426     <li>Message: <input type="text" name="message" /></li>
427     <li>Sender: <input type="text" name="sender" /></li>
428     <li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
429     >>> print f.as_p()
430     <p>Subject: <input type="text" name="subject" maxlength="100" /></p>
431     <p>Message: <input type="text" name="message" /></p>
432     <p>Sender: <input type="text" name="sender" /></p>
433     <p>Cc myself: <input type="checkbox" name="cc_myself" /></p>
434
435 If ``auto_id`` is set to ``True``, then the form output *will* include
436 ``<label>`` tags and will simply use the field name as its ``id`` for each form
437 field::
438
439     >>> f = ContactForm(auto_id=True)
440     >>> print f.as_table()
441     <tr><th><label for="subject">Subject:</label></th><td><input id="subject" type="text" name="subject" maxlength="100" /></td></tr>
442     <tr><th><label for="message">Message:</label></th><td><input type="text" name="message" id="message" /></td></tr>
443     <tr><th><label for="sender">Sender:</label></th><td><input type="text" name="sender" id="sender" /></td></tr>
444     <tr><th><label for="cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="cc_myself" /></td></tr>
445     >>> print f.as_ul()
446     <li><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></li>
447     <li><label for="message">Message:</label> <input type="text" name="message" id="message" /></li>
448     <li><label for="sender">Sender:</label> <input type="text" name="sender" id="sender" /></li>
449     <li><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></li>
450     >>> print f.as_p()
451     <p><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></p>
452     <p><label for="message">Message:</label> <input type="text" name="message" id="message" /></p>
453     <p><label for="sender">Sender:</label> <input type="text" name="sender" id="sender" /></p>
454     <p><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></p>
455
456 If ``auto_id`` is set to a string containing the format character ``'%s'``,
457 then the form output will include ``<label>`` tags, and will generate ``id``
458 attributes based on the format string. For example, for a format string
459 ``'field_%s'``, a field named ``subject`` will get the ``id`` value
460 ``'field_subject'``. Continuing our example::
461
462     >>> f = ContactForm(auto_id='id_for_%s')
463     >>> print f.as_table()
464     <tr><th><label for="id_for_subject">Subject:</label></th><td><input id="id_for_subject" type="text" name="subject" maxlength="100" /></td></tr>
465     <tr><th><label for="id_for_message">Message:</label></th><td><input type="text" name="message" id="id_for_message" /></td></tr>
466     <tr><th><label for="id_for_sender">Sender:</label></th><td><input type="text" name="sender" id="id_for_sender" /></td></tr>
467     <tr><th><label for="id_for_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></td></tr>
468     >>> print f.as_ul()
469     <li><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
470     <li><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></li>
471     <li><label for="id_for_sender">Sender:</label> <input type="text" name="sender" id="id_for_sender" /></li>
472     <li><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
473     >>> print f.as_p()
474     <p><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></p>
475     <p><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></p>
476     <p><label for="id_for_sender">Sender:</label> <input type="text" name="sender" id="id_for_sender" /></p>
477     <p><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></p>
478
479 If ``auto_id`` is set to any other true value -- such as a string that doesn't
480 include ``%s`` -- then the library will act as if ``auto_id`` is ``True``.
481
482 By default, ``auto_id`` is set to the string ``'id_%s'``.
483
484 Normally, a colon (``:``) will be appended after any label name when a form is
485 rendered. It's possible to change the colon to another character, or omit it
486 entirely, using the ``label_suffix`` parameter::
487
488     >>> f = ContactForm(auto_id='id_for_%s', label_suffix='')
489     >>> print f.as_ul()
490     <li><label for="id_for_subject">Subject</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
491     <li><label for="id_for_message">Message</label> <input type="text" name="message" id="id_for_message" /></li>
492     <li><label for="id_for_sender">Sender</label> <input type="text" name="sender" id="id_for_sender" /></li>
493     <li><label for="id_for_cc_myself">Cc myself</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
494     >>> f = ContactForm(auto_id='id_for_%s', label_suffix=' ->')
495     >>> print f.as_ul()
496     <li><label for="id_for_subject">Subject -></label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
497     <li><label for="id_for_message">Message -></label> <input type="text" name="message" id="id_for_message" /></li>
498     <li><label for="id_for_sender">Sender -></label> <input type="text" name="sender" id="id_for_sender" /></li>
499     <li><label for="id_for_cc_myself">Cc myself -></label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
500
501 Note that the label suffix is added only if the last character of the
502 label isn't a punctuation character (``.``, ``!``, ``?`` or ``:``)
503
504 Notes on field ordering
505 ~~~~~~~~~~~~~~~~~~~~~~~
506
507 In the ``as_p()``, ``as_ul()`` and ``as_table()`` shortcuts, the fields are
508 displayed in the order in which you define them in your form class. For
509 example, in the ``ContactForm`` example, the fields are defined in the order
510 ``subject``, ``message``, ``sender``, ``cc_myself``. To reorder the HTML
511 output, just change the order in which those fields are listed in the class.
512
513 How errors are displayed
514 ~~~~~~~~~~~~~~~~~~~~~~~~
515
516 If you render a bound ``Form`` object, the act of rendering will automatically
517 run the form's validation if it hasn't already happened, and the HTML output
518 will include the validation errors as a ``<ul class="errorlist">`` near the
519 field. The particular positioning of the error messages depends on the output
520 method you're using::
521
522     >>> data = {'subject': '',
523     ...         'message': 'Hi there',
524     ...         'sender': 'invalid e-mail address',
525     ...         'cc_myself': True}
526     >>> f = ContactForm(data, auto_id=False)
527     >>> print f.as_table()
528     <tr><th>Subject:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" /></td></tr>
529     <tr><th>Message:</th><td><input type="text" name="message" value="Hi there" /></td></tr>
530     <tr><th>Sender:</th><td><ul class="errorlist"><li>Enter a valid e-mail address.</li></ul><input type="text" name="sender" value="invalid e-mail address" /></td></tr>
531     <tr><th>Cc myself:</th><td><input checked="checked" type="checkbox" name="cc_myself" /></td></tr>
532     >>> print f.as_ul()
533     <li><ul class="errorlist"><li>This field is required.</li></ul>Subject: <input type="text" name="subject" maxlength="100" /></li>
534     <li>Message: <input type="text" name="message" value="Hi there" /></li>
535     <li><ul class="errorlist"><li>Enter a valid e-mail address.</li></ul>Sender: <input type="text" name="sender" value="invalid e-mail address" /></li>
536     <li>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></li>
537     >>> print f.as_p()
538     <p><ul class="errorlist"><li>This field is required.</li></ul></p>
539     <p>Subject: <input type="text" name="subject" maxlength="100" /></p>
540     <p>Message: <input type="text" name="message" value="Hi there" /></p>
541     <p><ul class="errorlist"><li>Enter a valid e-mail address.</li></ul></p>
542     <p>Sender: <input type="text" name="sender" value="invalid e-mail address" /></p>
543     <p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p>
544
545 Customizing the error list format
546 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
547
548 By default, forms use ``django.forms.util.ErrorList`` to format validation
549 errors. If you'd like to use an alternate class for displaying errors, you can
550 pass that in at construction time::
551
552     >>> from django.forms.util import ErrorList
553     >>> class DivErrorList(ErrorList):
554     ...     def __unicode__(self):
555     ...         return self.as_divs()
556     ...     def as_divs(self):
557     ...         if not self: return u''
558     ...         return u'<div class="errorlist">%s</div>' % ''.join([u'<div class="error">%s</div>' % e for e in self])
559     >>> f = ContactForm(data, auto_id=False, error_class=DivErrorList)
560     >>> f.as_p()
561     <div class="errorlist"><div class="error">This field is required.</div></div>
562     <p>Subject: <input type="text" name="subject" maxlength="100" /></p>
563     <p>Message: <input type="text" name="message" value="Hi there" /></p>
564     <div class="errorlist"><div class="error">Enter a valid e-mail address.</div></div>
565     <p>Sender: <input type="text" name="sender" value="invalid e-mail address" /></p>
566     <p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p>
567
568 More granular output
569 ~~~~~~~~~~~~~~~~~~~~
570
571 The ``as_p()``, ``as_ul()`` and ``as_table()`` methods are simply shortcuts for
572 lazy developers -- they're not the only way a form object can be displayed.
573
574 To display the HTML for a single field in your form, use dictionary lookup
575 syntax using the field's name as the key, and print the resulting object::
576
577     >>> f = ContactForm()
578     >>> print f['subject']
579     <input id="id_subject" type="text" name="subject" maxlength="100" />
580     >>> print f['message']
581     <input type="text" name="message" id="id_message" />
582     >>> print f['sender']
583     <input type="text" name="sender" id="id_sender" />
584     >>> print f['cc_myself']
585     <input type="checkbox" name="cc_myself" id="id_cc_myself" />
586
587 Call ``str()`` or ``unicode()`` on the field to get its rendered HTML as a
588 string or Unicode object, respectively::
589
590     >>> str(f['subject'])
591     '<input id="id_subject" type="text" name="subject" maxlength="100" />'
592     >>> unicode(f['subject'])
593     u'<input id="id_subject" type="text" name="subject" maxlength="100" />'
594
595 The field-specific output honors the form object's ``auto_id`` setting::
596
597     >>> f = ContactForm(auto_id=False)
598     >>> print f['message']
599     <input type="text" name="message" />
600     >>> f = ContactForm(auto_id='id_%s')
601     >>> print f['message']
602     <input type="text" name="message" id="id_message" />
603
604 For a field's list of errors, access the field's ``errors`` attribute. This
605 is a list-like object that is displayed as an HTML ``<ul class="errorlist">``
606 when printed::
607
608     >>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''}
609     >>> f = ContactForm(data, auto_id=False)
610     >>> print f['message']
611     <input type="text" name="message" />
612     >>> f['message'].errors
613     [u'This field is required.']
614     >>> print f['message'].errors
615     <ul class="errorlist"><li>This field is required.</li></ul>
616     >>> f['subject'].errors
617     []
618     >>> print f['subject'].errors
619
620     >>> str(f['subject'].errors)
621     ''
622
623 Using forms in views and templates
624 ----------------------------------
625
626 Let's put this all together and use the ``ContactForm`` example in a Django
627 view and template.
628
629 Simple view example
630 ~~~~~~~~~~~~~~~~~~~
631
632 This example view displays the contact form by default and validates/processes
633 it if accessed via a POST request::
634
635     def contact(request):
636         if request.method == 'POST':
637             form = ContactForm(request.POST)
638             if form.is_valid():
639                 # Do form processing here...
640                 return HttpResponseRedirect('/url/on_success/')
641         else:
642             form = ContactForm()
643         return render_to_response('contact.html', {'form': form})
644
645 Simple template example
646 ~~~~~~~~~~~~~~~~~~~~~~~
647
648 The template in the above view example, ``contact.html``, is responsible for
649 displaying the form as HTML. To do this, we can use the techniques outlined in
650 the "Outputting forms as HTML" section above.
651
652 The simplest way to display a form's HTML is to use the variable on its own,
653 like this::
654
655     <form method="post" action="">
656     <table>{{ form }}</table>
657     <input type="submit" />
658     </form>
659
660 The above template code will display the form as an HTML table, using the
661 ``form.as_table()`` method explained previously. This works because Django's
662 template system displays an object's ``__str__()`` value, and the ``Form``
663 class' ``__str__()`` method calls its ``as_table()`` method.
664
665 The following is equivalent but a bit more explicit::
666
667     <form method="post" action="">
668     <table>{{ form.as_table }}</table>
669     <input type="submit" />
670     </form>
671
672 ``form.as_ul`` and ``form.as_p`` are also available, as you may expect.
673
674 Note that in the above two examples, we included the ``<form>``, ``<table>``
675 ``<input type="submit" />``, ``</table>`` and ``</form>`` tags. The form
676 convenience methods (``as_table()``, ``as_ul()`` and ``as_p()``) do not include
677 that HTML.
678
679 Complex template output
680 ~~~~~~~~~~~~~~~~~~~~~~~
681
682 As we've stressed several times, the ``as_table()``, ``as_ul()`` and ``as_p()``
683 methods are just shortcuts for the common case. You can also work with the
684 individual fields for complete template control over the form's design.
685
686 The easiest way is to iterate over the form's fields, with
687 ``{% for field in form %}``. For example::
688
689     <form method="post" action="">
690     <dl>
691     {% for field in form %}
692         <dt>{{ field.label_tag }}</dt>
693         <dd>{{ field }}</dd>
694         {% if field.help_text %}<dd>{{ field.help_text }}</dd>{% endif %}
695         {% if field.errors %}<dd class="myerrors">{{ field.errors }}</dd>{% endif %}
696     {% endfor %}
697     </dl>
698     <input type="submit" />
699     </form>
700
701 This iteration technique is useful if you want to apply the same HTML
702 formatting to each field, or if you don't know the names of the form fields
703 ahead of time. Note that the fields will be iterated over in the order in which
704 they're defined in the ``Form`` class.
705
706 Alternatively, you can arrange the form's fields explicitly, by name. Do that
707 by accessing ``{{ form.fieldname }}``, where ``fieldname`` is the field's name.
708 For example::
709
710     <form method="post" action="">
711     <ul class="myformclass">
712         <li>{{ form.sender.label_tag }} {{ form.sender }}</li>
713         <li class="helptext">{{ form.sender.help_text }}</li>
714         {% if form.sender.errors %}<ul class="errorlist">{{ form.sender.errors }}</ul>{% endif %}
715
716         <li>{{ form.subject.label_tag }} {{ form.subject }}</li>
717         <li class="helptext">{{ form.subject.help_text }}</li>
718         {% if form.subject.errors %}<ul class="errorlist">{{ form.subject.errors }}</ul>{% endif %}
719
720         ...
721     </ul>
722     </form>
723
724 Highlighting required fields in templates
725 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
726
727 It's common to show a user which fields are required. Here's an example of how
728 to do that, using the above example modified to insert an asterisk after the
729 label of each required field::
730
731     <form method="post" action="">
732     <dl>
733     {% for field in form %}
734         <dt>{{ field.label_tag }}{% if field.field.required %}*{% endif %}</dt>
735         <dd>{{ field }}</dd>
736         {% if field.help_text %}<dd>{{ field.help_text }}</dd>{% endif %}
737         {% if field.errors %}<dd class="myerrors">{{ field.errors }}</dd>{% endif %}
738     {% endfor %}
739     </dl>
740     <input type="submit" />
741     </form>
742
743 The ``{% if field.field.required %}*{% endif %}`` fragment is the relevant
744 addition here. It adds the asterisk only if the field is required.
745
746 Note that we check ``field.field.required`` and not ``field.required``. In the
747 template, ``field`` is a ``forms.forms.BoundField`` instance, which holds
748 the actual ``Field`` instance in its ``field`` attribute.
749
750 Binding uploaded files to a form
751 --------------------------------
752
753 **New in Django development version**
754
755 Dealing with forms that have ``FileField`` and ``ImageField`` fields
756 is a little more complicated than a normal form.
757
758 Firstly, in order to upload files, you'll need to make sure that your
759 ``<form>`` element correctly defines the ``enctype`` as
760 ``"multipart/form-data"``::
761
762   <form enctype="multipart/form-data" method="post" action="/foo/">
763
764 Secondly, when you use the form, you need to bind the file data. File
765 data is handled separately to normal form data, so when your form
766 contains a ``FileField`` and ``ImageField``, you will need to specify
767 a second argument when you bind your form. So if we extend our
768 ContactForm to include an ``ImageField`` called ``mugshot``, we
769 need to bind the file data containing the mugshot image::
770
771     # Bound form with an image field
772     >>> from django.core.files.uploadedfile import SimpleUploadedFile
773     >>> data = {'subject': 'hello',
774     ...         'message': 'Hi there',
775     ...         'sender': 'foo@example.com',
776     ...         'cc_myself': True}
777     >>> file_data = {'mugshot': SimpleUploadedFile('face.jpg', <file data>)}
778     >>> f = ContactFormWithMugshot(data, file_data)
779
780 In practice, you will usually specify ``request.FILES`` as the source
781 of file data (just like you use ``request.POST`` as the source of
782 form data)::
783
784     # Bound form with an image field, data from the request
785     >>> f = ContactFormWithMugshot(request.POST, request.FILES)
786
787 Constructing an unbound form is the same as always -- just omit both
788 form data *and* file data::
789
790     # Unbound form with a image field
791     >>> f = ContactFormWithMugshot()
792
793 Testing for multipart forms
794 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
795
796 If you're writing reusable views or templates, you may not know ahead of time
797 whether your form is a multipart form or not. The ``is_multipart()`` method
798 tells you whether the form requires multipart encoding for submission::
799
800     >>> f = ContactFormWithMugshot()
801     >>> f.is_multipart()
802     True
803
804 Here's an example of how you might use this in a template::
805
806     {% if form.is_multipart %}
807         <form enctype="multipart/form-data" method="post" action="/foo/">
808     {% else %}
809         <form method="post" action="/foo/">
810     {% endif %}
811     {{ form }}
812     </form>
813
814 Subclassing forms
815 -----------------
816
817 If you have multiple ``Form`` classes that share fields, you can use
818 subclassing to remove redundancy.
819
820 When you subclass a custom ``Form`` class, the resulting subclass will
821 include all fields of the parent class(es), followed by the fields you define
822 in the subclass.
823
824 In this example, ``ContactFormWithPriority`` contains all the fields from
825 ``ContactForm``, plus an additional field, ``priority``. The ``ContactForm``
826 fields are ordered first::
827
828     >>> class ContactFormWithPriority(ContactForm):
829     ...     priority = forms.CharField()
830     >>> f = ContactFormWithPriority(auto_id=False)
831     >>> print f.as_ul()
832     <li>Subject: <input type="text" name="subject" maxlength="100" /></li>
833     <li>Message: <input type="text" name="message" /></li>
834     <li>Sender: <input type="text" name="sender" /></li>
835     <li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
836     <li>Priority: <input type="text" name="priority" /></li>
837
838 It's possible to subclass multiple forms, treating forms as "mix-ins." In this
839 example, ``BeatleForm`` subclasses both ``PersonForm`` and ``InstrumentForm``
840 (in that order), and its field list includes the fields from the parent
841 classes::
842
843     >>> class PersonForm(Form):
844     ...     first_name = CharField()
845     ...     last_name = CharField()
846     >>> class InstrumentForm(Form):
847     ...     instrument = CharField()
848     >>> class BeatleForm(PersonForm, InstrumentForm):
849     ...     haircut_type = CharField()
850     >>> b = BeatleForm(auto_id=False)
851     >>> print b.as_ul()
852     <li>First name: <input type="text" name="first_name" /></li>
853     <li>Last name: <input type="text" name="last_name" /></li>
854     <li>Instrument: <input type="text" name="instrument" /></li>
855     <li>Haircut type: <input type="text" name="haircut_type" /></li>
856
857 Prefixes for forms
858 ------------------
859
860 You can put several Django forms inside one ``<form>`` tag. To give each
861 ``Form`` its own namespace, use the ``prefix`` keyword argument::
862
863     >>> mother = PersonForm(prefix="mother")
864     >>> father = PersonForm(prefix="father")
865     >>> print mother.as_ul()
866     <li><label for="id_mother-first_name">First name:</label> <input type="text" name="mother-first_name" id="id_mother-first_name" /></li>
867     <li><label for="id_mother-last_name">Last name:</label> <input type="text" name="mother-last_name" id="id_mother-last_name" /></li>
868     >>> print father.as_ul()
869     <li><label for="id_father-first_name">First name:</label> <input type="text" name="father-first_name" id="id_father-first_name" /></li>
870     <li><label for="id_father-last_name">Last name:</label> <input type="text" name="father-last_name" id="id_father-last_name" /></li>
871
872 Fields
873 ======
874
875 When you create a ``Form`` class, the most important part is defining the
876 fields of the form. Each field has custom validation logic, along with a few
877 other hooks.
878
879 Although the primary way you'll use ``Field`` classes is in ``Form`` classes,
880 you can also instantiate them and use them directly to get a better idea of
881 how they work. Each ``Field`` instance has a ``clean()`` method, which takes
882 a single argument and either raises a ``django.forms.ValidationError``
883 exception or returns the clean value::
884
885     >>> f = forms.EmailField()
886     >>> f.clean('foo@example.com')
887     u'foo@example.com'
888     >>> f.clean(u'foo@example.com')
889     u'foo@example.com'
890     >>> f.clean('invalid e-mail address')
891     Traceback (most recent call last):
892     ...
893     ValidationError: [u'Enter a valid e-mail address.']
894
895 If you've used Django's old forms/validation framework, take care in noticing
896 this ``ValidationError`` is different than the previous ``ValidationError``.
897 This one lives at ``django.forms.ValidationError`` rather than
898 ``django.core.validators.ValidationError``.
899
900 Core field arguments
901 --------------------
902
903 Each ``Field`` class constructor takes at least these arguments. Some
904 ``Field`` classes take additional, field-specific arguments, but the following
905 should *always* be accepted:
906
907 ``required``
908 ~~~~~~~~~~~~
909
910 By default, each ``Field`` class assumes the value is required, so if you pass
911 an empty value -- either ``None`` or the empty string (``""``) -- then
912 ``clean()`` will raise a ``ValidationError`` exception::
913
914     >>> f = forms.CharField()
915     >>> f.clean('foo')
916     u'foo'
917     >>> f.clean('')
918     Traceback (most recent call last):
919     ...
920     ValidationError: [u'This field is required.']
921     >>> f.clean(None)
922     Traceback (most recent call last):
923     ...
924     ValidationError: [u'This field is required.']
925     >>> f.clean(' ')
926     u' '
927     >>> f.clean(0)
928     u'0'
929     >>> f.clean(True)
930     u'True'
931     >>> f.clean(False)
932     u'False'
933
934 To specify that a field is *not* required, pass ``required=False`` to the
935 ``Field`` constructor::
936
937     >>> f = forms.CharField(required=False)
938     >>> f.clean('foo')
939     u'foo'
940     >>> f.clean('')
941     u''
942     >>> f.clean(None)
943     u''
944     >>> f.clean(0)
945     u'0'
946     >>> f.clean(True)
947     u'True'
948     >>> f.clean(False)
949     u'False'
950
951 If a ``Field`` has ``required=False`` and you pass ``clean()`` an empty value,
952 then ``clean()`` will return a *normalized* empty value rather than raising
953 ``ValidationError``. For ``CharField``, this will be a Unicode empty string.
954 For other ``Field`` classes, it might be ``None``. (This varies from field to
955 field.)
956
957 ``label``
958 ~~~~~~~~~
959
960 The ``label`` argument lets you specify the "human-friendly" label for this
961 field. This is used when the ``Field`` is displayed in a ``Form``.
962
963 As explained in "Outputting forms as HTML" above, the default label for a
964 ``Field`` is generated from the field name by converting all underscores to
965 spaces and upper-casing the first letter. Specify ``label`` if that default
966 behavior doesn't result in an adequate label.
967
968 Here's a full example ``Form`` that implements ``label`` for two of its fields.
969 We've specified ``auto_id=False`` to simplify the output::
970
971     >>> class