Remove an extraneous comma that I left behind in [7386], and clean up the wording...
[django.git] / docs / newforms.txt
blobd07f7f9dc351304a03a03faae153507468da42de
1 ====================
2 The newforms library
3 ====================
5 ``django.newforms`` is Django's fantastic new form-handling library. It's a
6 replacement for ``django.forms``, the old form/manipulator/validation
7 framework. This document explains how to use this new library.
9 Migration plan
10 ==============
12 ``django.newforms`` is new in Django's 0.96 release, but, as it won't be new
13 forever, we plan to rename it to ``django.forms`` in the future. The current
14 ``django.forms`` package will be available as ``django.oldforms`` until Django
15 1.0, when we plan to remove it for good.
17 That has direct repercussions on the forward compatibility of your code. Please
18 read the following migration plan and code accordingly:
20     * The old forms framework (the current ``django.forms``) has been copied to
21       ``django.oldforms``. Thus, you can start upgrading your code *now*,
22       rather than waiting for the future backwards-incompatible change, by
23       changing your import statements like this::
25           from django import forms             # old
26           from django import oldforms as forms # new
28     * In the next Django release (0.97), we will move the current
29       ``django.newforms`` to ``django.forms``. This will be a
30       backwards-incompatible change, and anybody who is still using the old
31       version of ``django.forms`` at that time will need to change their import
32       statements, as described in the previous bullet.
34     * We will remove ``django.oldforms`` in the release *after* the next Django
35       release -- either 0.98 or 1.0, whichever comes first.
37 With this in mind, we recommend you use the following import statement when
38 using ``django.newforms``::
40     from django import newforms as forms
42 This way, your code can refer to the ``forms`` module, and when
43 ``django.newforms`` is renamed to ``django.forms``, you'll only have to change
44 your ``import`` statements.
46 If you prefer "``import *``" syntax, you can do the following::
48     from django.newforms import *
50 This will import all fields, widgets, form classes and other various utilities
51 into your local namespace. Some people find this convenient; others find it
52 too messy. The choice is yours.
54 Overview
55 ========
57 As with the ``django.forms`` ("manipulators") system before it,
58 ``django.newforms`` is intended to handle HTML form display, data processing
59 (validation) and redisplay. It's what you use if you want to perform
60 server-side validation for an HTML form.
62 For example, if your Web site has a contact form that visitors can use to
63 send you e-mail, you'd use this library to implement the display of the HTML
64 form fields, along with the form validation. Any time you need to use an HTML
65 ``<form>``, you can use this library.
67 The library deals with these concepts:
69     * **Widget** -- A class that corresponds to an HTML form widget, e.g.
70       ``<input type="text">`` or ``<textarea>``. This handles rendering of the
71       widget as HTML.
73     * **Field** -- A class that is responsible for doing validation, e.g.
74       an ``EmailField`` that makes sure its data is a valid e-mail address.
76     * **Form** -- A collection of fields that knows how to validate itself and
77       display itself as HTML.
79 The library is decoupled from the other Django components, such as the database
80 layer, views and templates. It relies only on Django settings, a couple of
81 ``django.utils`` helper functions and Django's internationalization hooks (but
82 you're not required to be using internationalization features to use this
83 library).
85 Form objects
86 ============
88 The primary way of using the ``newforms`` library is to create a form object.
89 Do this by subclassing ``django.newforms.Form`` and specifying the form's
90 fields, in a declarative style that you'll be familiar with if you've used
91 Django database models. In this section, we'll iteratively develop a form
92 object that you might use to implement "contact me" functionality on your
93 personal Web site.
95 Start with this basic ``Form`` subclass, which we'll call ``ContactForm``::
97     from django import newforms as forms
99     class ContactForm(forms.Form):
100         subject = forms.CharField(max_length=100)
101         message = forms.CharField()
102         sender = forms.EmailField()
103         cc_myself = forms.BooleanField(required=False)
105 A form is composed of ``Field`` objects. In this case, our form has four
106 fields: ``subject``, ``message``, ``sender`` and ``cc_myself``. We'll explain
107 the different types of fields -- e.g., ``CharField`` and ``EmailField`` --
108 shortly.
110 Creating ``Form`` instances
111 ---------------------------
113 A ``Form`` instance is either **bound** to a set of data, or **unbound**.
115     * If it's **bound** to a set of data, it's capable of validating that data
116       and rendering the form as HTML with the data displayed in the HTML.
118     * If it's **unbound**, it cannot do validation (because there's no data to
119       validate!), but it can still render the blank form as HTML.
121 To create an unbound ``Form`` instance, simply instantiate the class::
123     >>> f = ContactForm()
125 To bind data to a form, pass the data as a dictionary as the first parameter to
126 your ``Form`` class constructor::
128     >>> data = {'subject': 'hello',
129     ...         'message': 'Hi there',
130     ...         'sender': 'foo@example.com',
131     ...         'cc_myself': True}
132     >>> f = ContactForm(data)
134 In this dictionary, the keys are the field names, which correspond to the
135 attributes in your ``Form`` class. The values are the data you're trying
136 to validate. These will usually be strings, but there's no requirement that
137 they be strings; the type of data you pass depends on the ``Field``, as we'll
138 see in a moment.
140 If you need to distinguish between bound and unbound form instances at runtime,
141 check the value of the form's ``is_bound`` attribute::
143     >>> f = ContactForm()
144     >>> f.is_bound
145     False
146     >>> f = ContactForm({'subject': 'hello'})
147     >>> f.is_bound
148     True
150 Note that passing an empty dictionary creates a *bound* form with empty data::
152     >>> f = ContactForm({})
153     >>> f.is_bound
154     True
156 If you have a bound ``Form`` instance and want to change the data somehow, or
157 if you want to bind an unbound ``Form`` instance to some data, create another
158 ``Form`` instance. There is no way to change data in a ``Form`` instance. Once
159 a ``Form`` instance has been created, you should consider its data immutable,
160 whether it has data or not.
162 Using forms to validate data
163 ----------------------------
165 The primary task of a ``Form`` object is to validate data. With a bound
166 ``Form`` instance, call the ``is_valid()`` method to run validation and return
167 a boolean designating whether the data was valid::
169     >>> data = {'subject': 'hello',
170     ...         'message': 'Hi there',
171     ...         'sender': 'foo@example.com',
172     ...         'cc_myself': True}
173     >>> f = ContactForm(data)
174     >>> f.is_valid()
175     True
177 Let's try with some invalid data. In this case, ``subject`` is blank (an error,
178 because all fields are required by default) and ``sender`` is not a valid
179 e-mail address::
181     >>> data = {'subject': '',
182     ...         'message': 'Hi there',
183     ...         'sender': 'invalid e-mail address',
184     ...         'cc_myself': True}
185     >>> f = ContactForm(data)
186     >>> f.is_valid()
187     False
189 Access the ``errors`` attribute to get a dictionary of error messages::
191     >>> f.errors
192     {'sender': [u'Enter a valid e-mail address.'], 'subject': [u'This field is required.']}
194 In this dictionary, the keys are the field names, and the values are lists of
195 Unicode strings representing the error messages. The error messages are stored
196 in lists because a field can have multiple error messages.
198 You can access ``errors`` without having to call ``is_valid()`` first. The
199 form's data will be validated the first time either you call ``is_valid()`` or
200 access ``errors``.
202 The validation routines will only get called once, regardless of how many times
203 you access ``errors`` or call ``is_valid()``. This means that if validation has
204 side effects, those side effects will only be triggered once.
206 Behavior of unbound forms
207 ~~~~~~~~~~~~~~~~~~~~~~~~~
209 It's meaningless to validate a form with no data, but, for the record, here's
210 what happens with unbound forms::
212     >>> f = ContactForm()
213     >>> f.is_valid()
214     False
215     >>> f.errors
216     {}
218 Accessing "clean" data
219 ----------------------
221 Each ``Field`` in a ``Form`` class is responsible not only for validating data,
222 but also for "cleaning" it -- normalizing it to a consistent format. This is a
223 nice feature, because it allows data for a particular field to be input in
224 a variety of ways, always resulting in consistent output.
226 For example, ``DateField`` normalizes input into a Python ``datetime.date``
227 object. Regardless of whether you pass it a string in the format
228 ``'1994-07-15'``, a ``datetime.date`` object or a number of other formats,
229 ``DateField`` will always normalize it to a ``datetime.date`` object as long as
230 it's valid.
232 Once you've created a ``Form`` instance with a set of data and validated it,
233 you can access the clean data via the ``cleaned_data`` attribute of the ``Form``
234 object::
236     >>> data = {'subject': 'hello',
237     ...         'message': 'Hi there',
238     ...         'sender': 'foo@example.com',
239     ...         'cc_myself': True}
240     >>> f = ContactForm(data)
241     >>> f.is_valid()
242     True
243     >>> f.cleaned_data
244     {'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'}
246 .. note::
247     **New in Django development version** The ``cleaned_data`` attribute was
248     called ``clean_data`` in earlier releases.
250 Note that any text-based field -- such as ``CharField`` or ``EmailField`` --
251 always cleans the input into a Unicode string. We'll cover the encoding
252 implications later in this document.
254 If your data does *not* validate, your ``Form`` instance will not have a
255 ``cleaned_data`` attribute::
257     >>> data = {'subject': '',
258     ...         'message': 'Hi there',
259     ...         'sender': 'invalid e-mail address',
260     ...         'cc_myself': True}
261     >>> f = ContactForm(data)
262     >>> f.is_valid()
263     False
264     >>> f.cleaned_data
265     Traceback (most recent call last):
266     ...
267     AttributeError: 'ContactForm' object has no attribute 'cleaned_data'
269 ``cleaned_data`` will always *only* contain a key for fields defined in the
270 ``Form``, even if you pass extra data when you define the ``Form``. In this
271 example, we pass a bunch of extra fields to the ``ContactForm`` constructor,
272 but ``cleaned_data`` contains only the form's fields::
274     >>> data = {'subject': 'hello',
275     ...         'message': 'Hi there',
276     ...         'sender': 'foo@example.com',
277     ...         'cc_myself': True,
278     ...         'extra_field_1': 'foo',
279     ...         'extra_field_2': 'bar',
280     ...         'extra_field_3': 'baz'}
281     >>> f = ContactForm(data)
282     >>> f.is_valid()
283     True
284     >>> f.cleaned_data # Doesn't contain extra_field_1, etc.
285     {'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'}
287 ``cleaned_data`` will include a key and value for *all* fields defined in the
288 ``Form``, even if the data didn't include a value for fields that are not
289 required. In this example, the data dictionary doesn't include a value for the
290 ``nick_name`` field, but ``cleaned_data`` includes it, with an empty value::
292     >>> class OptionalPersonForm(Form):
293     ...     first_name = CharField()
294     ...     last_name = CharField()
295     ...     nick_name = CharField(required=False)
296     >>> data = {'first_name': u'John', 'last_name': u'Lennon'}
297     >>> f = OptionalPersonForm(data)
298     >>> f.is_valid()
299     True
300     >>> f.cleaned_data
301     {'nick_name': u'', 'first_name': u'John', 'last_name': u'Lennon'}
303 In this above example, the ``cleaned_data`` value for ``nick_name`` is set to an
304 empty string, because ``nick_name`` is ``CharField``, and ``CharField``\s treat
305 empty values as an empty string. Each field type knows what its "blank" value
306 is -- e.g., for ``DateField``, it's ``None`` instead of the empty string. For
307 full details on each field's behavior in this case, see the "Empty value" note
308 for each field in the "Built-in ``Field`` classes" section below.
310 You can write code to perform validation for particular form fields (based on
311 their name) or for the form as a whole (considering combinations of various
312 fields). More information about this is in the `Custom form and field
313 validation`_ section, below.
315 Behavior of unbound forms
316 ~~~~~~~~~~~~~~~~~~~~~~~~~
318 It's meaningless to request "cleaned" data in a form with no data, but, for the
319 record, here's what happens with unbound forms::
321     >>> f = ContactForm()
322     >>> f.cleaned_data
323     Traceback (most recent call last):
324     ...
325     AttributeError: 'ContactForm' object has no attribute 'cleaned_data'
327 Outputting forms as HTML
328 ------------------------
330 The second task of a ``Form`` object is to render itself as HTML. To do so,
331 simply ``print`` it::
333     >>> f = ContactForm()
334     >>> print f
335     <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
336     <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
337     <tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr>
338     <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>
340 If the form is bound to data, the HTML output will include that data
341 appropriately. For example, if a field is represented by an
342 ``<input type="text">``, the data will be in the ``value`` attribute. If a
343 field is represented by an ``<input type="checkbox">``, then that HTML will
344 include ``checked="checked"`` if appropriate::
346     >>> data = {'subject': 'hello',
347     ...         'message': 'Hi there',
348     ...         'sender': 'foo@example.com',
349     ...         'cc_myself': True}
350     >>> f = ContactForm(data)
351     >>> print f
352     <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" value="hello" /></td></tr>
353     <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" value="Hi there" /></td></tr>
354     <tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" value="foo@example.com" /></td></tr>
355     <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>
357 This default output is a two-column HTML table, with a ``<tr>`` for each field.
358 Notice the following:
360     * For flexibility, the output does *not* include the ``<table>`` and
361       ``</table>`` tags, nor does it include the ``<form>`` and ``</form>``
362       tags or an ``<input type="submit">`` tag. It's your job to do that.
364     * Each field type has a default HTML representation. ``CharField`` and
365       ``EmailField`` are represented by an ``<input type="text">``.
366       ``BooleanField`` is represented by an ``<input type="checkbox">``. Note
367       these are merely sensible defaults; you can specify which HTML to use for
368       a given field by using widgets, which we'll explain shortly.
370     * The HTML ``name`` for each tag is taken directly from its attribute name
371       in the ``ContactForm`` class.
373     * The text label for each field -- e.g. ``'Subject:'``, ``'Message:'`` and
374       ``'Cc myself:'`` is generated from the field name by converting all
375       underscores to spaces and upper-casing the first letter. Again, note
376       these are merely sensible defaults; you can also specify labels manually.
378     * Each text label is surrounded in an HTML ``<label>`` tag, which points
379       to the appropriate form field via its ``id``. Its ``id``, in turn, is
380       generated by prepending ``'id_'`` to the field name. The ``id``
381       attributes and ``<label>`` tags are included in the output by default, to
382       follow best practices, but you can change that behavior.
384 Although ``<table>`` output is the default output style when you ``print`` a
385 form, other output styles are available. Each style is available as a method on
386 a form object, and each rendering method returns a Unicode object.
388 ``as_p()``
389 ~~~~~~~~~~
391 ``Form.as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>``
392 containing one field::
394     >>> f = ContactForm()
395     >>> f.as_p()
396     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>'
397     >>> print f.as_p()
398     <p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>
399     <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>
400     <p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p>
401     <p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>
403 ``as_ul()``
404 ~~~~~~~~~~~
406 ``Form.as_ul()`` renders the form as a series of ``<li>`` tags, with each
407 ``<li>`` containing one field. It does *not* include the ``<ul>`` or ``</ul>``,
408 so that you can specify any HTML attributes on the ``<ul>`` for flexibility::
410     >>> f = ContactForm()
411     >>> f.as_ul()
412     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>'
413     >>> print f.as_ul()
414     <li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>
415     <li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>
416     <li><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></li>
417     <li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>
419 ``as_table()``
420 ~~~~~~~~~~~~~~
422 Finally, ``Form.as_table()`` outputs the form as an HTML ``<table>``. This is
423 exactly the same as ``print``. In fact, when you ``print`` a form object, it
424 calls its ``as_table()`` method behind the scenes::
426     >>> f = ContactForm()
427     >>> f.as_table()
428     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>'
429     >>> print f.as_table()
430     <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
431     <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
432     <tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr>
433     <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>
435 Configuring HTML ``<label>`` tags
436 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
438 An HTML ``<label>`` tag designates which label text is associated with which
439 form element. This small enhancement makes forms more usable and more accessible
440 to assistive devices. It's always a good idea to use ``<label>`` tags.
442 By default, the form rendering methods include HTML ``id`` attributes on the
443 form elements and corresponding ``<label>`` tags around the labels. The ``id``
444 attribute values are generated by prepending ``id_`` to the form field names.
445 This behavior is configurable, though, if you want to change the ``id``
446 convention or remove HTML ``id`` attributes and ``<label>`` tags entirely.
448 Use the ``auto_id`` argument to the ``Form`` constructor to control the label
449 and ``id`` behavior. This argument must be ``True``, ``False`` or a string.
451 If ``auto_id`` is ``False``, then the form output will not include ``<label>``
452 tags nor ``id`` attributes::
454     >>> f = ContactForm(auto_id=False)
455     >>> print f.as_table()
456     <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /></td></tr>
457     <tr><th>Message:</th><td><input type="text" name="message" /></td></tr>
458     <tr><th>Sender:</th><td><input type="text" name="sender" /></td></tr>
459     <tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr>
460     >>> print f.as_ul()
461     <li>Subject: <input type="text" name="subject" maxlength="100" /></li>
462     <li>Message: <input type="text" name="message" /></li>
463     <li>Sender: <input type="text" name="sender" /></li>
464     <li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
465     >>> print f.as_p()
466     <p>Subject: <input type="text" name="subject" maxlength="100" /></p>
467     <p>Message: <input type="text" name="message" /></p>
468     <p>Sender: <input type="text" name="sender" /></p>
469     <p>Cc myself: <input type="checkbox" name="cc_myself" /></p>
471 If ``auto_id`` is set to ``True``, then the form output *will* include
472 ``<label>`` tags and will simply use the field name as its ``id`` for each form
473 field::
475     >>> f = ContactForm(auto_id=True)
476     >>> print f.as_table()
477     <tr><th><label for="subject">Subject:</label></th><td><input id="subject" type="text" name="subject" maxlength="100" /></td></tr>
478     <tr><th><label for="message">Message:</label></th><td><input type="text" name="message" id="message" /></td></tr>
479     <tr><th><label for="sender">Sender:</label></th><td><input type="text" name="sender" id="sender" /></td></tr>
480     <tr><th><label for="cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="cc_myself" /></td></tr>
481     >>> print f.as_ul()
482     <li><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></li>
483     <li><label for="message">Message:</label> <input type="text" name="message" id="message" /></li>
484     <li><label for="sender">Sender:</label> <input type="text" name="sender" id="sender" /></li>
485     <li><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></li>
486     >>> print f.as_p()
487     <p><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></p>
488     <p><label for="message">Message:</label> <input type="text" name="message" id="message" /></p>
489     <p><label for="sender">Sender:</label> <input type="text" name="sender" id="sender" /></p>
490     <p><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></p>
492 If ``auto_id`` is set to a string containing the format character ``'%s'``,
493 then the form output will include ``<label>`` tags, and will generate ``id``
494 attributes based on the format string. For example, for a format string
495 ``'field_%s'``, a field named ``subject`` will get the ``id`` value
496 ``'field_subject'``. Continuing our example::
498     >>> f = ContactForm(auto_id='id_for_%s')
499     >>> print f.as_table()
500     <tr><th><label for="id_for_subject">Subject:</label></th><td><input id="id_for_subject" type="text" name="subject" maxlength="100" /></td></tr>
501     <tr><th><label for="id_for_message">Message:</label></th><td><input type="text" name="message" id="id_for_message" /></td></tr>
502     <tr><th><label for="id_for_sender">Sender:</label></th><td><input type="text" name="sender" id="id_for_sender" /></td></tr>
503     <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>
504     >>> print f.as_ul()
505     <li><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
506     <li><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></li>
507     <li><label for="id_for_sender">Sender:</label> <input type="text" name="sender" id="id_for_sender" /></li>
508     <li><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
509     >>> print f.as_p()
510     <p><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></p>
511     <p><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></p>
512     <p><label for="id_for_sender">Sender:</label> <input type="text" name="sender" id="id_for_sender" /></p>
513     <p><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></p>
515 If ``auto_id`` is set to any other true value -- such as a string that doesn't
516 include ``%s`` -- then the library will act as if ``auto_id`` is ``True``.
518 By default, ``auto_id`` is set to the string ``'id_%s'``.
520 Normally, a colon (``:``) will be appended after any label name when a form is
521 rendered. It's possible to change the colon to another character, or omit it
522 entirely, using the ``label_suffix`` parameter::
524     >>> f = ContactForm(auto_id='id_for_%s', label_suffix='')
525     >>> print f.as_ul()
526     <li><label for="id_for_subject">Subject</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
527     <li><label for="id_for_message">Message</label> <input type="text" name="message" id="id_for_message" /></li>
528     <li><label for="id_for_sender">Sender</label> <input type="text" name="sender" id="id_for_sender" /></li>
529     <li><label for="id_for_cc_myself">Cc myself</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
530     >>> f = ContactForm(auto_id='id_for_%s', label_suffix=' ->')
531     >>> print f.as_ul()
532     <li><label for="id_for_subject">Subject -></label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
533     <li><label for="id_for_message">Message -></label> <input type="text" name="message" id="id_for_message" /></li>
534     <li><label for="id_for_sender">Sender -></label> <input type="text" name="sender" id="id_for_sender" /></li>
535     <li><label for="id_for_cc_myself">Cc myself -></label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
537 Note that the label suffix is added only if the last character of the
538 label isn't a punctuation character (``.``, ``!``, ``?`` or ``:``)
540 Notes on field ordering
541 ~~~~~~~~~~~~~~~~~~~~~~~
543 In the ``as_p()``, ``as_ul()`` and ``as_table()`` shortcuts, the fields are
544 displayed in the order in which you define them in your form class. For
545 example, in the ``ContactForm`` example, the fields are defined in the order
546 ``subject``, ``message``, ``sender``, ``cc_myself``. To reorder the HTML
547 output, just change the order in which those fields are listed in the class.
549 How errors are displayed
550 ~~~~~~~~~~~~~~~~~~~~~~~~
552 If you render a bound ``Form`` object, the act of rendering will automatically
553 run the form's validation if it hasn't already happened, and the HTML output
554 will include the validation errors as a ``<ul class="errorlist">`` near the
555 field. The particular positioning of the error messages depends on the output
556 method you're using::
558     >>> data = {'subject': '',
559     ...         'message': 'Hi there',
560     ...         'sender': 'invalid e-mail address',
561     ...         'cc_myself': True}
562     >>> f = ContactForm(data, auto_id=False)
563     >>> print f.as_table()
564     <tr><th>Subject:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" /></td></tr>
565     <tr><th>Message:</th><td><input type="text" name="message" value="Hi there" /></td></tr>
566     <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>
567     <tr><th>Cc myself:</th><td><input checked="checked" type="checkbox" name="cc_myself" /></td></tr>
568     >>> print f.as_ul()
569     <li><ul class="errorlist"><li>This field is required.</li></ul>Subject: <input type="text" name="subject" maxlength="100" /></li>
570     <li>Message: <input type="text" name="message" value="Hi there" /></li>
571     <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>
572     <li>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></li>
573     >>> print f.as_p()
574     <p><ul class="errorlist"><li>This field is required.</li></ul></p>
575     <p>Subject: <input type="text" name="subject" maxlength="100" /></p>
576     <p>Message: <input type="text" name="message" value="Hi there" /></p>
577     <p><ul class="errorlist"><li>Enter a valid e-mail address.</li></ul></p>
578     <p>Sender: <input type="text" name="sender" value="invalid e-mail address" /></p>
579     <p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p>
581 Customizing the error list format
582 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
584 By default, forms use ``django.newforms.util.ErrorList`` to format validation
585 errors. If you'd like to use an alternate class for displaying errors, you can
586 pass that in at construction time::
588     >>> from django.newforms.util import ErrorList
589     >>> class DivErrorList(ErrorList):
590     ...     def __unicode__(self):
591     ...         return self.as_divs()
592     ...     def as_divs(self):
593     ...         if not self: return u''
594     ...         return u'<div class="errorlist">%s</div>' % ''.join([u'<div class="error">%s</div>' % e for e in self])
595     >>> f = ContactForm(data, auto_id=False, error_class=DivErrorList)
596     >>> f.as_p()
597     <div class="errorlist"><div class="error">This field is required.</div></div>
598     <p>Subject: <input type="text" name="subject" maxlength="100" /></p>
599     <p>Message: <input type="text" name="message" value="Hi there" /></p>
600     <div class="errorlist"><div class="error">Enter a valid e-mail address.</div></div>
601     <p>Sender: <input type="text" name="sender" value="invalid e-mail address" /></p>
602     <p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p>
604 More granular output
605 ~~~~~~~~~~~~~~~~~~~~
607 The ``as_p()``, ``as_ul()`` and ``as_table()`` methods are simply shortcuts for
608 lazy developers -- they're not the only way a form object can be displayed.
610 To display the HTML for a single field in your form, use dictionary lookup
611 syntax using the field's name as the key, and print the resulting object::
613     >>> f = ContactForm()
614     >>> print f['subject']
615     <input id="id_subject" type="text" name="subject" maxlength="100" />
616     >>> print f['message']
617     <input type="text" name="message" id="id_message" />
618     >>> print f['sender']
619     <input type="text" name="sender" id="id_sender" />
620     >>> print f['cc_myself']
621     <input type="checkbox" name="cc_myself" id="id_cc_myself" />
623 Call ``str()`` or ``unicode()`` on the field to get its rendered HTML as a
624 string or Unicode object, respectively::
626     >>> str(f['subject'])
627     '<input id="id_subject" type="text" name="subject" maxlength="100" />'
628     >>> unicode(f['subject'])
629     u'<input id="id_subject" type="text" name="subject" maxlength="100" />'
631 The field-specific output honors the form object's ``auto_id`` setting::
633     >>> f = ContactForm(auto_id=False)
634     >>> print f['message']
635     <input type="text" name="message" />
636     >>> f = ContactForm(auto_id='id_%s')
637     >>> print f['message']
638     <input type="text" name="message" id="id_message" />
640 For a field's list of errors, access the field's ``errors`` attribute. This
641 is a list-like object that is displayed as an HTML ``<ul class="errorlist">``
642 when printed::
644     >>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''}
645     >>> f = ContactForm(data, auto_id=False)
646     >>> print f['message']
647     <input type="text" name="message" />
648     >>> f['message'].errors
649     [u'This field is required.']
650     >>> print f['message'].errors
651     <ul class="errorlist"><li>This field is required.</li></ul>
652     >>> f['subject'].errors
653     []
654     >>> print f['subject'].errors
656     >>> str(f['subject'].errors)
657     ''
659 Using forms in views and templates
660 ----------------------------------
662 Let's put this all together and use the ``ContactForm`` example in a Django
663 view and template.
665 Simple view example
666 ~~~~~~~~~~~~~~~~~~~
668 This example view displays the contact form by default and validates/processes
669 it if accessed via a POST request::
671     def contact(request):
672         if request.method == 'POST':
673             form = ContactForm(request.POST)
674             if form.is_valid():
675                 # Do form processing here...
676                 return HttpResponseRedirect('/url/on_success/')
677         else:
678             form = ContactForm()
679         return render_to_response('contact.html', {'form': form})
681 Simple template example
682 ~~~~~~~~~~~~~~~~~~~~~~~
684 The template in the above view example, ``contact.html``, is responsible for
685 displaying the form as HTML. To do this, we can use the techniques outlined in
686 the "Outputting forms as HTML" section above.
688 The simplest way to display a form's HTML is to use the variable on its own,
689 like this::
691     <form method="post" action="">
692     <table>{{ form }}</table>
693     <input type="submit" />
694     </form>
696 The above template code will display the form as an HTML table, using the
697 ``form.as_table()`` method explained previously. This works because Django's
698 template system displays an object's ``__str__()`` value, and the ``Form``
699 class' ``__str__()`` method calls its ``as_table()`` method.
701 The following is equivalent but a bit more explicit::
703     <form method="post" action="">
704     <table>{{ form.as_table }}</table>
705     <input type="submit" />
706     </form>
708 ``form.as_ul`` and ``form.as_p`` are also available, as you may expect.
710 Note that in the above two examples, we included the ``<form>``, ``<table>``
711 ``<input type="submit" />``, ``</table>`` and ``</form>`` tags. The form
712 convenience methods (``as_table()``, ``as_ul()`` and ``as_p()``) do not include
713 that HTML.
715 Complex template output
716 ~~~~~~~~~~~~~~~~~~~~~~~
718 As we've stressed several times, the ``as_table()``, ``as_ul()`` and ``as_p()``
719 methods are just shortcuts for the common case. You can also work with the
720 individual fields for complete template control over the form's design.
722 The easiest way is to iterate over the form's fields, with
723 ``{% for field in form %}``. For example::
725     <form method="post" action="">
726     <dl>
727     {% for field in form %}
728         <dt>{{ field.label_tag }}</dt>
729         <dd>{{ field }}</dd>
730         {% if field.help_text %}<dd>{{ field.help_text }}</dd>{% endif %}
731         {% if field.errors %}<dd class="myerrors">{{ field.errors }}</dd>{% endif %}
732     {% endfor %}
733     </dl>
734     <input type="submit" />
735     </form>
737 This iteration technique is useful if you want to apply the same HTML
738 formatting to each field, or if you don't know the names of the form fields
739 ahead of time. Note that the fields will be iterated over in the order in which
740 they're defined in the ``Form`` class.
742 Alternatively, you can arrange the form's fields explicitly, by name. Do that
743 by accessing ``{{ form.fieldname }}``, where ``fieldname`` is the field's name.
744 For example::
746     <form method="post" action="">
747     <ul class="myformclass">
748         <li>{{ form.sender.label_tag }} {{ form.sender }}</li>
749         <li class="helptext">{{ form.sender.help_text }}</li>
750         {% if form.sender.errors %}<ul class="errorlist">{{ form.sender.errors }}</ul>{% endif %}
752         <li>{{ form.subject.label_tag }} {{ form.subject }}</li>
753         <li class="helptext">{{ form.subject.help_text }}</li>
754         {% if form.subject.errors %}<ul class="errorlist">{{ form.subject.errors }}</ul>{% endif %}
756         ...
757     </ul>
758     </form>
760 Highlighting required fields in templates
761 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
763 It's common to show a user which fields are required. Here's an example of how
764 to do that, using the above example modified to insert an asterisk after the
765 label of each required field::
767     <form method="post" action="">
768     <dl>
769     {% for field in form %}
770         <dt>{{ field.label_tag }}{% if field.field.required %}*{% endif %}</dt>
771         <dd>{{ field }}</dd>
772         {% if field.help_text %}<dd>{{ field.help_text }}</dd>{% endif %}
773         {% if field.errors %}<dd class="myerrors">{{ field.errors }}</dd>{% endif %}
774     {% endfor %}
775     </dl>
776     <input type="submit" />
777     </form>
779 The ``{% if field.field.required %}*{% endif %}`` fragment is the relevant
780 addition here. It adds the asterisk only if the field is required.
782 Note that we check ``field.field.required`` and not ``field.required``. In the
783 template, ``field`` is a ``newforms.forms.BoundField`` instance, which holds
784 the actual ``Field`` instance in its ``field`` attribute.
786 Binding uploaded files to a form
787 --------------------------------
789 **New in Django development version**
791 Dealing with forms that have ``FileField`` and ``ImageField`` fields
792 is a little more complicated than a normal form.
794 Firstly, in order to upload files, you'll need to make sure that your
795 ``<form>`` element correctly defines the ``enctype`` as
796 ``"multipart/form-data"``::
798   <form enctype="multipart/form-data" method="post" action="/foo/">
800 Secondly, when you use the form, you need to bind the file data. File
801 data is handled separately to normal form data, so when your form
802 contains a ``FileField`` and ``ImageField``, you will need to specify
803 a second argument when you bind your form. So if we extend our
804 ContactForm to include an ``ImageField`` called ``mugshot``, we
805 need to bind the file data containing the mugshot image::
807     # Bound form with an image field
808     >>> data = {'subject': 'hello',
809     ...         'message': 'Hi there',
810     ...         'sender': 'foo@example.com',
811     ...         'cc_myself': True}
812     >>> file_data = {'mugshot': {'filename':'face.jpg'
813     ...                          'content': <file data>}}
814     >>> f = ContactFormWithMugshot(data, file_data)
816 In practice, you will usually specify ``request.FILES`` as the source
817 of file data (just like you use ``request.POST`` as the source of
818 form data)::
820     # Bound form with an image field, data from the request
821     >>> f = ContactFormWithMugshot(request.POST, request.FILES)
823 Constructing an unbound form is the same as always -- just omit both
824 form data *and* file data::
826     # Unbound form with a image field
827     >>> f = ContactFormWithMugshot()
829 Testing for multipart forms
830 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
832 If you're writing reusable views or templates, you may not know ahead of time
833 whether your form is a multipart form or not. The ``is_multipart()`` method
834 tells you whether the form requires multipart encoding for submission::
836     >>> f = ContactFormWithMugshot()
837     >>> f.is_multipart()
838     True
840 Here's an example of how you might use this in a template::
842     {% if form.is_multipart %}
843         <form enctype="multipart/form-data" method="post" action="/foo/">
844     {% else %}
845         <form method="post" action="/foo/">
846     {% endif %}
847     {% form %}
848     </form>
850 Subclassing forms
851 -----------------
853 If you have multiple ``Form`` classes that share fields, you can use
854 subclassing to remove redundancy.
856 When you subclass a custom ``Form`` class, the resulting subclass will
857 include all fields of the parent class(es), followed by the fields you define
858 in the subclass.
860 In this example, ``ContactFormWithPriority`` contains all the fields from
861 ``ContactForm``, plus an additional field, ``priority``. The ``ContactForm``
862 fields are ordered first::
864     >>> class ContactFormWithPriority(ContactForm):
865     ...     priority = forms.CharField()
866     >>> f = ContactFormWithPriority(auto_id=False)
867     >>> print f.as_ul()
868     <li>Subject: <input type="text" name="subject" maxlength="100" /></li>
869     <li>Message: <input type="text" name="message" /></li>
870     <li>Sender: <input type="text" name="sender" /></li>
871     <li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
872     <li>Priority: <input type="text" name="priority" /></li>
874 It's possible to subclass multiple forms, treating forms as "mix-ins." In this
875 example, ``BeatleForm`` subclasses both ``PersonForm`` and ``InstrumentForm``
876 (in that order), and its field list includes the fields from the parent
877 classes::
879     >>> class PersonForm(Form):
880     ...     first_name = CharField()
881     ...     last_name = CharField()
882     >>> class InstrumentForm(Form):
883     ...     instrument = CharField()
884     >>> class BeatleForm(PersonForm, InstrumentForm):
885     ...     haircut_type = CharField()
886     >>> b = BeatleForm(auto_id=False)
887     >>> print b.as_ul()
888     <li>First name: <input type="text" name="first_name" /></li>
889     <li>Last name: <input type="text" name="last_name" /></li>
890     <li>Instrument: <input type="text" name="instrument" /></li>
891     <li>Haircut type: <input type="text" name="haircut_type" /></li>
893 Prefixes for forms
894 ------------------
896 You can put several Django forms inside one ``<form>`` tag. To give each
897 ``Form`` its own namespace, use the ``prefix`` keyword argument::
899     >>> mother = PersonForm(prefix="mother")
900     >>> father = PersonForm(prefix="father")
901     >>> print mother.as_ul()
902     <li><label for="id_mother-first_name">First name:</label> <input type="text" name="mother-first_name" id="id_mother-first_name" /></li>
903     <li><label for="id_mother-last_name">Last name:</label> <input type="text" name="mother-last_name" id="id_mother-last_name" /></li>
904     >>> print father.as_ul()
905     <li><label for="id_father-first_name">First name:</label> <input type="text" name="father-first_name" id="id_father-first_name" /></li>
906     <li><label for="id_father-last_name">Last name:</label> <input type="text" name="father-last_name" id="id_father-last_name" /></li>
908 Fields
909 ======
911 When you create a ``Form`` class, the most important part is defining the
912 fields of the form. Each field has custom validation logic, along with a few
913 other hooks.
915 Although the primary way you'll use ``Field`` classes is in ``Form`` classes,
916 you can also instantiate them and use them directly to get a better idea of
917 how they work. Each ``Field`` instance has a ``clean()`` method, which takes
918 a single argument and either raises a ``django.newforms.ValidationError``
919 exception or returns the clean value::
921     >>> f = forms.EmailField()
922     >>> f.clean('foo@example.com')
923     u'foo@example.com'
924     >>> f.clean(u'foo@example.com')
925     u'foo@example.com'
926     >>> f.clean('invalid e-mail address')
927     Traceback (most recent call last):
928     ...
929     ValidationError: [u'Enter a valid e-mail address.']
931 If you've used Django's old forms/validation framework, take care in noticing
932 this ``ValidationError`` is different than the previous ``ValidationError``.
933 This one lives at ``django.newforms.ValidationError`` rather than
934 ``django.core.validators.ValidationError``.
936 Core field arguments
937 --------------------
939 Each ``Field`` class constructor takes at least these arguments. Some
940 ``Field`` classes take additional, field-specific arguments, but the following
941 should *always* be accepted:
943 ``required``
944 ~~~~~~~~~~~~
946 By default, each ``Field`` class assumes the value is required, so if you pass
947 an empty value -- either ``None`` or the empty string (``""``) -- then
948 ``clean()`` will raise a ``ValidationError`` exception::
950     >>> f = forms.CharField()
951     >>> f.clean('foo')
952     u'foo'
953     >>> f.clean('')
954     Traceback (most recent call last):
955     ...
956     ValidationError: [u'This field is required.']
957     >>> f.clean(None)
958     Traceback (most recent call last):
959     ...
960     ValidationError: [u'This field is required.']
961     >>> f.clean(' ')
962     u' '
963     >>> f.clean(0)
964     u'0'
965     >>> f.clean(True)
966     u'True'
967     >>> f.clean(False)
968     u'False'
970 To specify that a field is *not* required, pass ``required=False`` to the
971 ``Field`` constructor::
973     >>> f = forms.CharField(required=False)
974     >>> f.clean('foo')
975     u'foo'
976     >>> f.clean('')
977     u''
978     >>> f.clean(None)
979     u''
980     >>> f.clean(0)
981     u'0'
982     >>> f.clean(True)
983     u'True'
984     >>> f.clean(False)
985     u'False'
987 If a ``Field`` has ``required=False`` and you pass ``clean()`` an empty value,
988 then ``clean()`` will return a *normalized* empty value rather than raising
989 ``ValidationError``. For ``CharField``, this will be a Unicode empty string.
990 For other ``Field`` classes, it might be ``None``. (This varies from field to
991 field.)
993 ``label``
994 ~~~~~~~~~
996 The ``label`` argument lets you specify the "human-friendly" label for this
997 field. This is used when the ``Field`` is displayed in a ``Form``.
999 As explained in "Outputting forms as HTML" above, the default label for a
1000 ``Field`` is generated from the field name by converting all underscores to
1001 spaces and upper-casing the first letter. Specify ``label`` if that default
1002 behavior doesn't result in an adequate label.
1004 Here's a full example ``Form`` that implements ``label`` for two of its fields.
1005 We've specified ``auto_id=False`` to simplify the output::
1007     >>> class CommentForm(forms.Form):
1008     ...     name = forms.CharField(label='Your name')
1009     ...     url = forms.URLField(label='Your Web site', required=False)
1010     ...     comment = forms.CharField()
1011     >>> f = CommentForm(auto_id=False)
1012     >>> print f
1013     <tr><th>Your name:</th><td><input type="text" name="name" /></td></tr>
1014     <tr><th>Your Web site:</th><td><input type="text" name="url" /></td></tr>
1015     <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
1017 ``initial``
1018 ~~~~~~~~~~~
1020 The ``initial`` argument lets you specify the initial value to use when
1021 rendering this ``Field`` in an unbound ``Form``.
1023 The use-case for this is when you want to display an "empty" form in which a
1024 field is initialized to a particular value. For example::
1026     >>> class CommentForm(forms.Form):
1027     ...     name = forms.CharField(initial='Your name')
1028     ...     url = forms.URLField(initial='http://')
1029     ...     comment = forms.CharField()
1030     >>> f = CommentForm(auto_id=False)
1031     >>> print f
1032     <tr><th>Name:</th><td><input type="text" name="name" value="Your name" /></td></tr>
1033     <tr><th>Url:</th><td><input type="text" name="url" value="http://" /></td></tr>
1034     <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
1036 You may be thinking, why not just pass a dictionary of the initial values as
1037 data when displaying the form? Well, if you do that, you'll trigger validation,
1038 and the HTML output will include any validation errors::
1040     >>> class CommentForm(forms.Form):
1041     ...     name = forms.CharField()
1042     ...     url = forms.URLField()
1043     ...     comment = forms.CharField()
1044     >>> default_data = {'name': 'Your name', 'url': 'http://'}
1045     >>> f = CommentForm(default_data, auto_id=False)
1046     >>> print f
1047     <tr><th>Name:</th><td><input type="text" name="name" value="Your name" /></td></tr>
1048     <tr><th>Url:</th><td><ul class="errorlist"><li>Enter a valid URL.</li></ul><input type="text" name="url" value="http://" /></td></tr>
1049     <tr><th>Comment:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="comment" /></td></tr>
1051 This is why ``initial`` values are only displayed for unbound forms. For bound
1052 forms, the HTML output will use the bound data.
1054 Also note that ``initial`` values are *not* used as "fallback" data in
1055 validation if a particular field's value is not given. ``initial`` values are
1056 *only* intended for initial form display::
1058     >>> class CommentForm(forms.Form):
1059     ...     name = forms.CharField(initial='Your name')
1060     ...     url = forms.URLField(initial='http://')
1061     ...     comment = forms.CharField()
1062     >>> data = {'name': '', 'url': '', 'comment': 'Foo'}
1063     >>> f = CommentForm(data)
1064     >>> f.is_valid()
1065     False
1066     # The form does *not* fall back to using the initial values.
1067     >>> f.errors
1068     {'url': [u'This field is required.'], 'name': [u'This field is required.']}
1070 ``widget``
1071 ~~~~~~~~~~
1073 The ``widget`` argument lets you specify a ``Widget`` class to use when
1074 rendering this ``Field``. See `Widgets`_ below for more information.
1076 ``help_text``
1077 ~~~~~~~~~~~~~
1079 The ``help_text`` argument lets you specify descriptive text for this
1080 ``Field``. If you provide ``help_text``, it will be displayed next to the
1081 ``Field`` when the ``Field`` is rendered by one of the convenience ``Form``
1082 methods (e.g., ``as_ul()``).
1084 Here's a full example ``Form`` that implements ``help_text`` for two of its
1085 fields. We've specified ``auto_id=False`` to simplify the output::
1087     >>> class HelpTextContactForm(forms.Form):
1088     ...     subject = forms.CharField(max_length=100, help_text='100 characters max.')
1089     ...     message = forms.CharField()
1090     ...     sender = forms.EmailField(help_text='A valid e-mail address, please.')
1091     ...     cc_myself = forms.BooleanField(required=False)
1092     >>> f = HelpTextContactForm(auto_id=False)
1093     >>> print f.as_table()
1094     <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /><br />100 characters max.</td></tr>
1095     <tr><th>Message:</th><td><input type="text" name="message" /></td></tr>
1096     <tr><th>Sender:</th><td><input type="text" name="sender" /><br />A valid e-mail address, please.</td></tr>
1097     <tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr>
1098     >>> print f.as_ul()
1099     <li>Subject: <input type="text" name="subject" maxlength="100" /> 100 characters max.</li>
1100     <li>Message: <input type="text" name="message" /></li>
1101     <li>Sender: <input type="text" name="sender" /> A valid e-mail address, please.</li>
1102     <li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
1103     >>> print f.as_p()
1104     <p>Subject: <input type="text" name="subject" maxlength="100" /> 100 characters max.</p>
1105     <p>Message: <input type="text" name="message" /></p>
1106     <p>Sender: <input type="text" name="sender" /> A valid e-mail address, please.</p>
1107     <p>Cc myself: <input type="checkbox" name="cc_myself" /></p>
1109 ``error_messages``
1110 ~~~~~~~~~~~~~~~~~~
1112 **New in Django development version**
1114 The ``error_messages`` argument lets you override the default messages that the
1115 field will raise. Pass in a dictionary with keys matching the error messages you
1116 want to override. For example, here is the default error message::
1118     >>> generic = forms.CharField()
1119     >>> generic.clean('')
1120     Traceback (most recent call last):
1121       ...
1122     ValidationError: [u'This field is required.']
1124 And here is a custom error message::
1126     >>> name = forms.CharField(error_messages={'required': 'Please enter your name'})
1127     >>> name.clean('')
1128     Traceback (most recent call last):
1129       ...
1130     ValidationError: [u'Please enter your name']
1132 In the `built-in Field classes`_ section below, each ``Field`` defines the
1133 error message keys it uses.
1135 Dynamic initial values
1136 ----------------------
1138 The ``initial`` argument to ``Field`` (explained above) lets you hard-code the
1139 initial value for a ``Field`` -- but what if you want to declare the initial
1140 value at runtime? For example, you might want to fill in a ``username`` field
1141 with the username of the current session.
1143 To accomplish this, use the ``initial`` argument to a ``Form``. This argument,
1144 if given, should be a dictionary mapping field names to initial values. Only
1145 include the fields for which you're specifying an initial value; it's not
1146 necessary to include every field in your form. For example::
1148     >>> class CommentForm(forms.Form):
1149     ...     name = forms.CharField()
1150     ...     url = forms.URLField()
1151     ...     comment = forms.CharField()
1152     >>> f = CommentForm(initial={'name': 'your username'}, auto_id=False)
1153     >>> print f
1154     <tr><th>Name:</th><td><input type="text" name="name" value="your username" /></td></tr>
1155     <tr><th>Url:</th><td><input type="text" name="url" /></td></tr>
1156     <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
1157     >>> f = CommentForm(initial={'name': 'another username'}, auto_id=False)
1158     >>> print f
1159     <tr><th>Name:</th><td><input type="text" name="name" value="another username" /></td></tr>
1160     <tr><th>Url:</th><td><input type="text" name="url" /></td></tr>
1161     <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
1163 Just like the ``initial`` parameter to ``Field``, these values are only
1164 displayed for unbound forms, and they're not used as fallback values if a
1165 particular value isn't provided.
1167 Finally, note that if a ``Field`` defines ``initial`` *and* you include
1168 ``initial`` when instantiating the ``Form``, then the latter ``initial`` will
1169 have precedence. In this example, ``initial`` is provided both at the field
1170 level and at the form instance level, and the latter gets precedence::
1172     >>> class CommentForm(forms.Form):
1173     ...     name = forms.CharField(initial='class')
1174     ...     url = forms.URLField()
1175     ...     comment = forms.CharField()
1176     >>> f = CommentForm(initial={'name': 'instance'}, auto_id=False)
1177     >>> print f
1178     <tr><th>Name:</th><td><input type="text" name="name" value="instance" /></td></tr>
1179     <tr><th>Url:</th><td><input type="text" name="url" /></td></tr>
1180     <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
1182 Built-in ``Field`` classes
1183 --------------------------
1185 Naturally, the ``newforms`` library comes with a set of ``Field`` classes that
1186 represent common validation needs. This section documents each built-in field.
1188 For each field, we describe the default widget used if you don't specify
1189 ``widget``. We also specify the value returned when you provide an empty value
1190 (see the section on ``required`` above to understand what that means).
1192 ``BooleanField``
1193 ~~~~~~~~~~~~~~~~
1195     * Default widget: ``CheckboxInput``
1196     * Empty value: ``False``
1197     * Normalizes to: A Python ``True`` or ``False`` value.
1198     * Validates that the check box is checked (i.e. the value is ``True``) if
1199       the field has ``required=True``.
1200     * Error message keys: ``required``
1202 **New in Django development version:** The empty value for a ``CheckboxInput``
1203 (and hence the standard ``BooleanField``) has changed to return ``False``
1204 instead of ``None`` in the development version.
1206 .. note::
1207     Since all ``Field`` subclasses have ``required=True`` by default, the
1208     validation condition here is important. If you want to include a checkbox
1209     in your form that can be either checked or unchecked, you must remember to
1210     pass in ``required=False`` when creating the ``BooleanField``.
1212 ``CharField``
1213 ~~~~~~~~~~~~~
1215     * Default widget: ``TextInput``
1216     * Empty value: ``''`` (an empty string)
1217     * Normalizes to: A Unicode object.
1218     * Validates ``max_length`` or ``min_length``, if they are provided.
1219       Otherwise, all inputs are valid.
1220     * Error message keys: ``required``, ``max_length``, ``min_length``
1222 Has two optional arguments for validation, ``max_length`` and ``min_length``.
1223 If provided, these arguments ensure that the string is at most or at least the
1224 given length.
1226 ``ChoiceField``
1227 ~~~~~~~~~~~~~~~
1229     * Default widget: ``Select``
1230     * Empty value: ``''`` (an empty string)
1231     * Normalizes to: A Unicode object.
1232     * Validates that the given value exists in the list of choices.
1233     * Error message keys: ``required``, ``invalid_choice``
1235 Takes one extra argument, ``choices``, which is an iterable (e.g., a list or
1236 tuple) of 2-tuples to use as choices for this field.
1238 ``DateField``
1239 ~~~~~~~~~~~~~
1241     * Default widget: ``TextInput``
1242     * Empty value: ``None``
1243     * Normalizes to: A Python ``datetime.date`` object.
1244     * Validates that the given value is either a ``datetime.date``,
1245       ``datetime.datetime`` or string formatted in a particular date format.
1246     * Error message keys: ``required``, ``invalid``
1248 Takes one optional argument, ``input_formats``, which is a list of formats used
1249 to attempt to convert a string to a valid ``datetime.date`` object.
1251 If no ``input_formats`` argument is provided, the default input formats are::
1253     '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
1254     '%b %d %Y', '%b %d, %Y',            # 'Oct 25 2006', 'Oct 25, 2006'
1255     '%d %b %Y', '%d %b, %Y',            # '25 Oct 2006', '25 Oct, 2006'
1256     '%B %d %Y', '%B %d, %Y',            # 'October 25 2006', 'October 25, 2006'
1257     '%d %B %Y', '%d %B, %Y',            # '25 October 2006', '25 October, 2006'
1259 ``DateTimeField``
1260 ~~~~~~~~~~~~~~~~~
1262     * Default widget: ``DateTimeInput``
1263     * Empty value: ``None``
1264     * Normalizes to: A Python ``datetime.datetime`` object.
1265     * Validates that the given value is either a ``datetime.datetime``,
1266       ``datetime.date`` or string formatted in a particular datetime format.
1267     * Error message keys: ``required``, ``invalid``
1269 Takes one optional argument, ``input_formats``, which is a list of formats used
1270 to attempt to convert a string to a valid ``datetime.datetime`` object.
1272 If no ``input_formats`` argument is provided, the default input formats are::
1274     '%Y-%m-%d %H:%M:%S',     # '2006-10-25 14:30:59'
1275     '%Y-%m-%d %H:%M',        # '2006-10-25 14:30'
1276     '%Y-%m-%d',              # '2006-10-25'
1277     '%m/%d/%Y %H:%M:%S',     # '10/25/2006 14:30:59'
1278     '%m/%d/%Y %H:%M',        # '10/25/2006 14:30'
1279     '%m/%d/%Y',              # '10/25/2006'
1280     '%m/%d/%y %H:%M:%S',     # '10/25/06 14:30:59'
1281     '%m/%d/%y %H:%M',        # '10/25/06 14:30'
1282     '%m/%d/%y',              # '10/25/06'
1284 **New in Django development version:** The ``DateTimeField`` used to use a
1285 ``TextInput`` widget by default. This has now changed.
1287 ``DecimalField``
1288 ~~~~~~~~~~~~~~~~
1290 **New in Django development version**
1292     * Default widget: ``TextInput``
1293     * Empty value: ``None``
1294     * Normalizes to: A Python ``decimal``.
1295     * Validates that the given value is a decimal. Leading and trailing
1296       whitespace is ignored.
1297     * Error message keys: ``required``, ``invalid``, ``max_value``,
1298       ``min_value``, ``max_digits``, ``max_decimal_places``,
1299       ``max_whole_digits``
1301 Takes four optional arguments: ``max_value``, ``min_value``, ``max_digits``,
1302 and ``decimal_places``. The first two define the limits for the fields value.
1303 ``max_digits`` is the maximum number of digits (those before the decimal
1304 point plus those after the decimal point, with leading zeros stripped)
1305 permitted in the value, whilst ``decimal_places`` is the maximum number of
1306 decimal places permitted.
1308 ``EmailField``
1309 ~~~~~~~~~~~~~~
1311     * Default widget: ``TextInput``
1312     * Empty value: ``''`` (an empty string)
1313     * Normalizes to: A Unicode object.
1314     * Validates that the given value is a valid e-mail address, using a
1315       moderately complex regular expression.
1316     * Error message keys: ``required``, ``invalid``
1318 Has two optional arguments for validation, ``max_length`` and ``min_length``.
1319 If provided, these arguments ensure that the string is at most or at least the
1320 given length.
1322 ``FileField``
1323 ~~~~~~~~~~~~~
1325 **New in Django development version**
1327     * Default widget: ``FileInput``
1328     * Empty value: ``None``
1329     * Normalizes to: An ``UploadedFile`` object that wraps the file content
1330       and file name into a single object.
1331     * Validates that non-empty file data has been bound to the form.
1332     * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``
1334 An ``UploadedFile`` object has two attributes:
1336     ======================  ====================================================
1337     Attribute               Description
1338     ======================  ====================================================
1339     ``filename``            The name of the file, provided by the uploading
1340                             client.
1341                             
1342     ``content``             The array of bytes comprising the file content.
1343     ======================  ====================================================
1345 The string representation of an ``UploadedFile`` is the same as the filename
1346 attribute.
1348 When you use a ``FileField`` on a form, you must also remember to
1349 `bind the file data to the form`_.
1351 .. _`bind the file data to the form`: `Binding uploaded files to a form`_
1353 ``FilePathField``
1354 ~~~~~~~~~~~~~~~~~
1356 **New in Django development version**
1358     * Default widget: ``Select``
1359     * Empty value: ``None``
1360     * Normalizes to: A unicode object
1361     * Validates that the selected choice exists in the list of choices.
1362     * Error message keys: ``required``, ``invalid_choice``
1364 The field allows choosing from files inside a certain directory. It takes three
1365 extra arguments:
1367     ==============  ==========  ===============================================
1368     Argument        Required?   Description
1369     ==============  ==========  ===============================================
1370     ``path``        Yes         The absolute path to the directory whose 
1371                                 contents you want listed. This directory must 
1372                                 exist.
1373                             
1374     ``recursive``   No          If ``False`` (the default) only the direct
1375                                 contents of ``path`` will be offered as choices.
1376                                 If ``True``, the directory will be descended
1377                                 into recursively and all descendants will be
1378                                 listed as choices.
1379                                 
1380     ``match``       No          A regular expression pattern; only files with
1381                                 names matching this expression will be allowed
1382                                 as choices.
1383     ==============  ==========  ===============================================
1385 ``ImageField``
1386 ~~~~~~~~~~~~~~
1388 **New in Django development version**
1390     * Default widget: ``FileInput``
1391     * Empty value: ``None``
1392     * Normalizes to: An ``UploadedFile`` object that wraps the file content
1393       and file name into a single object.
1394     * Validates that file data has been bound to the form, and that the
1395       file is of an image format understood by PIL.
1396     * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,
1397       ``invalid_image``
1399 Using an ImageField requires that the `Python Imaging Library`_ is installed.
1401 When you use a ``FileField`` on a form, you must also remember to
1402 `bind the file data to the form`_.
1404 .. _Python Imaging Library: http://www.pythonware.com/products/pil/
1406 ``IntegerField``
1407 ~~~~~~~~~~~~~~~~
1409     * Default widget: ``TextInput``
1410     * Empty value: ``None``
1411     * Normalizes to: A Python integer or long integer.
1412     * Validates that the given value is an integer. Leading and trailing
1413       whitespace is allowed, as in Python's ``int()`` function.
1414     * Error message keys: ``required``, ``invalid``, ``max_value``,
1415       ``min_value``
1417 Takes two optional arguments for validation, ``max_value`` and ``min_value``.
1418 These control the range of values permitted in the field.
1420 ``IPAddressField``
1421 ~~~~~~~~~~~~~~~~~~
1423     * Default widget: ``TextInput``
1424     * Empty value: ``''`` (an empty string)
1425     * Normalizes to: A Unicode object.
1426     * Validates that the given value is a valid IPv4 address, using a regular
1427       expression.
1428     * Error message keys: ``required``, ``invalid``
1430 ``MultipleChoiceField``
1431 ~~~~~~~~~~~~~~~~~~~~~~~
1433     * Default widget: ``SelectMultiple``
1434     * Empty value: ``[]`` (an empty list)
1435     * Normalizes to: A list of Unicode objects.
1436     * Validates that every value in the given list of values exists in the list
1437       of choices.
1438     * Error message keys: ``required``, ``invalid_choice``, ``invalid_list``
1440 Takes one extra argument, ``choices``, which is an iterable (e.g., a list or
1441 tuple) of 2-tuples to use as choices for this field.
1443 ``NullBooleanField``
1444 ~~~~~~~~~~~~~~~~~~~~
1446     * Default widget: ``NullBooleanSelect``
1447     * Empty value: ``None``
1448     * Normalizes to: A Python ``True``, ``False`` or ``None`` value.
1449     * Validates nothing (i.e., it never raises a ``ValidationError``).
1451 ``RegexField``
1452 ~~~~~~~~~~~~~~
1454     * Default widget: ``TextInput``
1455     * Empty value: ``''`` (an empty string)
1456     * Normalizes to: A Unicode object.
1457     * Validates that the given value matches against a certain regular
1458       expression.
1459     * Error message keys: ``required``, ``invalid``
1461 Takes one required argument, ``regex``, which is a regular expression specified
1462 either as a string or a compiled regular expression object.
1464 Also takes the following optional arguments:
1466     ======================  =====================================================
1467     Argument                Description
1468     ======================  =====================================================
1469     ``max_length``          Ensures the string has at most this many characters.
1470     ``min_length``          Ensures the string has at least this many characters.
1471     ======================  =====================================================
1473 The optional argument ``error_message`` is also accepted for backwards
1474 compatibility. The preferred way to provide an error message is to use the
1475 ``error_messages`` argument, passing a dictionary with ``'invalid'`` as a key
1476 and the error message as the value.
1478 ``TimeField``
1479 ~~~~~~~~~~~~~
1481     * Default widget: ``TextInput``
1482     * Empty value: ``None``
1483     * Normalizes to: A Python ``datetime.time`` object.
1484     * Validates that the given value is either a ``datetime.time`` or string
1485       formatted in a particular time format.
1486     * Error message keys: ``required``, ``invalid``
1488 Takes one optional argument, ``input_formats``, which is a list of formats used
1489 to attempt to convert a string to a valid ``datetime.time`` object.
1491 If no ``input_formats`` argument is provided, the default input formats are::
1493     '%H:%M:%S',     # '14:30:59'
1494     '%H:%M',        # '14:30'
1496 ``URLField``
1497 ~~~~~~~~~~~~
1499     * Default widget: ``TextInput``
1500     * Empty value: ``''`` (an empty string)
1501     * Normalizes to: A Unicode object.
1502     * Validates that the given value is a valid URL.
1503     * Error message keys: ``required``, ``invalid``, ``invalid_link``
1505 Takes the following optional arguments:
1507     ========================  =====================================================
1508     Argument                  Description
1509     ========================  =====================================================
1510     ``max_length``            Ensures the string has at most this many characters.
1511     ``min_length``            Ensures the string has at least this many characters.
1512     ``verify_exists``         If ``True``, the validator will attempt to load the
1513                               given URL, raising ``ValidationError`` if the page
1514                               gives a 404. Defaults to ``False``.
1515     ``validator_user_agent``  String used as the user-agent used when checking for
1516                               a URL's existence. Defaults to the value of the
1517                               ``URL_VALIDATOR_USER_AGENT`` setting.
1518     ========================  =====================================================
1520 Slightly complex built-in ``Field`` classes
1521 -------------------------------------------
1523 The following are not yet documented here. See the unit tests, linked-to from
1524 the bottom of this document, for examples of their use.
1526 ``ComboField``
1527 ~~~~~~~~~~~~~~
1529 ``MultiValueField``
1530 ~~~~~~~~~~~~~~~~~~~
1532 ``SplitDateTimeField``
1533 ~~~~~~~~~~~~~~~~~~~~~~
1535 Fields which handle relationships
1536 ---------------------------------
1538 For representing relationships between models, two fields are
1539 provided which can derive their choices from a ``QuerySet``, and which
1540 place one or more model objects into the ``cleaned_data`` dictionary
1541 of forms in which they're used. Both of these fields have an
1542 additional required argument:
1544 ``queryset``
1545     A ``QuerySet`` of model objects from which the choices for the
1546     field will be derived, and which will be used to validate the
1547     user's selection.
1549 ``ModelChoiceField``
1550 ~~~~~~~~~~~~~~~~~~~~
1552 Allows the selection of a single model object, suitable for
1553 representing a foreign key.
1555 The ``__unicode__`` method of the model will be called to generate
1556 string representations of the objects for use in the field's choices;
1557 to provide customized representations, subclass ``ModelChoiceField``
1558 and override ``label_for_model``. This method will receive model
1559 object, and should return a string suitable for representing it::
1561     class MyModelChoiceField(ModelChoiceField):
1562         def label_from_instance(self, obj):
1563             return "My Object #%i" % obj.id
1565 ``ModelMultipleChoiceField``
1566 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1568 Allows the selection of one or more model objects, suitable for
1569 representing a many-to-many relation. As with ``ModelChoiceField``,
1570 you can use ``label_from_instance`` to customize the object
1571 representations.
1573 Creating custom fields
1574 ----------------------
1576 If the built-in ``Field`` classes don't meet your needs, you can easily create
1577 custom ``Field`` classes. To do this, just create a subclass of
1578 ``django.newforms.Field``. Its only requirements are that it implement a
1579 ``clean()`` method and that its ``__init__()`` method accept the core arguments
1580 mentioned above (``required``, ``label``, ``initial``, ``widget``,
1581 ``help_text``).
1583 Custom form and field validation
1584 ---------------------------------
1586 Form validation happens when the data is cleaned. If you want to customise
1587 this process, there are various places you can change, each one serving a
1588 different purpose. Three types of cleaning methods are run during form
1589 processing. These are normally executed when you call the ``is_valid()``
1590 method on a form. There are other things that can trigger cleaning and
1591 validation (accessing the ``errors`` attribute or calling ``full_clean()``
1592 directly), but normally they won't be needed.
1594 In general, any cleaning method can raise ``ValidationError`` if there is a
1595 problem with the data it is processing, passing the relevant error message to
1596 the ``ValidationError`` constructor. If no ``ValidationError`` is raised, the
1597 method should return the cleaned (normalised) data as a Python object.
1599 If you detect multiple errors during a cleaning method and wish to signal all
1600 of them to the form submitter, it is possible to pass a list of errors to the
1601 ``ValidationError`` constructor.
1603 The three types of cleaning methods are:
1605     * The ``clean()`` method on a Field subclass. This is responsible
1606       for cleaning the data in a way that is generic for that type of field.
1607       For example, a FloatField will turn the data into a Python ``float`` or
1608       raise a ``ValidationError``.
1610     * The ``clean_<fieldname>()`` method in a form subclass -- where
1611       ``<fieldname>`` is replaced with the name of the form field attribute.
1612       This method does any cleaning that is specific to that particular
1613       attribute, unrelated to the type of field that it is. This method is not
1614       passed any parameters. You will need to look up the value of the field
1615       in ``self.cleaned_data`` and remember that it will be a Python object
1616       at this point, not the original string submitted in the form (it will be
1617       in ``cleaned_data`` because the general field ``clean()`` method, above,
1618       has already cleaned the data once).
1620       For example, if you wanted to validate that the contents of a
1621       ``CharField`` called ``serialnumber`` was unique,
1622       ``clean_serialnumber()`` would be the right place to do this. You don't
1623       need a specific field (it's just a ``CharField``), but you want a
1624       formfield-specific piece of validation and, possibly,
1625       cleaning/normalizing the data.
1627     * The Form subclass's ``clean()`` method. This method can perform
1628       any validation that requires access to multiple fields from the form at
1629       once. This is where you might put in things to check that if field ``A``
1630       is supplied, field ``B`` must contain a valid email address and the
1631       like. The data that this method returns is the final ``cleaned_data``
1632       attribute for the form, so don't forget to return the full list of
1633       cleaned data if you override this method (by default, ``Form.clean()``
1634       just returns ``self.cleaned_data``).
1636       Note that any errors raised by your ``Form.clean()`` override will not
1637       be associated with any field in particular. They go into a special
1638       "field" (called ``__all__``), which you can access via the
1639       ``non_field_errors()`` method if you need to.
1641 These methods are run in the order given above, one field at a time.  That is,
1642 for each field in the form (in the order they are declared in the form
1643 definition), the ``Field.clean()`` method (or its override) is run, then
1644 ``clean_<fieldname>()``. Finally, once those two methods are run for every
1645 field, the ``Form.clean()`` method, or its override, is executed.
1647 As mentioned above, any of these methods can raise a ``ValidationError``. For
1648 any field, if the ``Field.clean()`` method raises a ``ValidationError``, any
1649 field-specific cleaning method is not called. However, the cleaning methods
1650 for all remaining fields are still executed.
1652 The ``clean()`` method for the ``Form`` class or subclass is always run. If
1653 that method raises a ``ValidationError``, ``cleaned_data`` will be an empty
1654 dictionary.
1656 The previous paragraph means that if you are overriding ``Form.clean()``, you
1657 should iterate through ``self.cleaned_data.items()``, possibly considering the
1658 ``_errors`` dictionary attribute on the form as well. In this way, you will
1659 already know which fields have passed their individual validation requirements.
1661 A simple example
1662 ~~~~~~~~~~~~~~~~
1664 Here's a simple example of a custom field that validates its input is a string
1665 containing comma-separated e-mail addresses, with at least one address. We'll
1666 keep it simple and assume e-mail validation is contained in a function called
1667 ``is_valid_email()``. The full class::
1669     from django import newforms as forms
1671     class MultiEmailField(forms.Field):
1672         def clean(self, value):
1673             if not value:
1674                 raise forms.ValidationError('Enter at least one e-mail address.')
1675             emails = value.split(',')
1676             for email in emails:
1677                 if not is_valid_email(email):
1678                     raise forms.ValidationError('%s is not a valid e-mail address.' % email)
1679             return emails
1681 Let's alter the ongoing ``ContactForm`` example to demonstrate how you'd use
1682 this in a form. Simply use ``MultiEmailField`` instead of ``forms.EmailField``,
1683 like so::
1685     class ContactForm(forms.Form):
1686         subject = forms.CharField(max_length=100)
1687         message = forms.CharField()
1688         senders = MultiEmailField()
1689         cc_myself = forms.BooleanField(required=False)
1691 Widgets
1692 =======
1694 A widget is Django's representation of a HTML input element. The widget
1695 handles the rendering of the HTML, and the extraction of data from a GET/POST
1696 dictionary that corresponds to the widget.
1698 Django provides a representation of all the basic HTML widgets, plus some
1699 commonly used groups of widgets:
1701     ============================  ===========================================
1702     Widget                        HTML Equivalent
1703     ============================  ===========================================
1704     ``TextInput``                 ``<input type='text' ...``
1705     ``PasswordInput``             ``<input type='password' ...``
1706     ``HiddenInput``               ``<input type='hidden' ...``
1707     ``MultipleHiddenInput``       Multiple ``<input type='hidden' ...``
1708                                   instances.
1709     ``FileInput``                 ``<input type='file' ...``
1710     ``DateTimeInput``             ``<input type='text' ...``
1711     ``Textarea``                  ``<textarea>...</textarea>``
1712     ``CheckboxInput``             ``<input type='checkbox' ...``
1713     ``Select``                    ``<select><option ...``
1714     ``NullBooleanSelect``         Select widget with options 'Unknown',
1715                                   'Yes' and 'No'
1716     ``SelectMultiple``            ``<select multiple='multiple'><option ...``
1717     ``RadioSelect``               ``<ul><li><input type='radio' ...``
1718     ``CheckboxSelectMultiple``    ``<ul><li><input type='checkbox' ...``
1719     ``MultiWidget``               Wrapper around multiple other widgets
1720     ``SplitDateTimeWidget``       Wrapper around two ``TextInput`` widgets:
1721                                   one for the Date, and one for the Time.
1722     ============================  ===========================================
1724 **New in Django development version:** The ``DateTimeInput`` has been added
1725 since the last release.
1727 Specifying widgets
1728 ------------------
1730 Whenever you specify a field on a form, Django will use a default widget
1731 that is appropriate to the type of data that is to be displayed. To find
1732 which widget is used on which field, see the documentation for the
1733 built-in Field classes.
1735 However, if you want to use a different widget for a field, you can -
1736 just use the 'widget' argument on the field definition. For example::
1738     class CommentForm(forms.Form):
1739         name = forms.CharField()
1740         url = forms.URLField()
1741         comment = forms.CharField(widget=forms.Textarea)
1743 This would specify a form with a comment that uses a larger Textarea widget,
1744 rather than the default TextInput widget.
1746 Customizing widget instances
1747 ----------------------------
1749 When Django renders a widget as HTML, it only renders the bare minimum
1750 HTML - Django doesn't add a class definition, or any other widget-specific
1751 attributes. This means that all 'TextInput' widgets will appear the same
1752 on your web page.
1754 If you want to make one widget look different to another, you need to
1755 specify additional attributes for each widget. When you specify a
1756 widget, you can provide a list of attributes that will be added to the
1757 rendered HTML for the widget.
1759 For example, take the following simple form::
1761     class CommentForm(forms.Form):
1762         name = forms.CharField()
1763         url = forms.URLField()
1764         comment = forms.CharField()
1766 This form will include three default TextInput widgets, with default rendering -
1767 no CSS class, no extra attributes. This means that the input boxes provided for
1768 each widget will be rendered exactly the same::
1770     >>> f = CommentForm(auto_id=False)
1771     >>> f.as_table()
1772     <tr><th>Name:</th><td><input type="text" name="name" /></td></tr>
1773     <tr><th>Url:</th><td><input type="text" name="url"/></td></tr>
1774     <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
1776 On a real web page, you probably don't want every widget to look the same. You
1777 might want a larger input element for the comment, and you might want the
1778 'name' widget to have some special CSS class. To do this, you specify a
1779 custom widget for your fields, and specify some attributes to use
1780 when rendering those widgets::
1782     class CommentForm(forms.Form):
1783         name = forms.CharField(
1784                     widget=forms.TextInput(attrs={'class':'special'}))
1785         url = forms.URLField()
1786         comment = forms.CharField(
1787                    widget=forms.TextInput(attrs={'size':'40'}))
1789 Django will then include the extra attributes in the rendered output::
1791     >>> f = CommentForm(auto_id=False)
1792     >>> f.as_table()
1793     <tr><th>Name:</th><td><input type="text" name="name" class="special"/></td></tr>
1794     <tr><th>Url:</th><td><input type="text" name="url"/></td></tr>
1795     <tr><th>Comment:</th><td><input type="text" name="comment" size="40"/></td></tr>
1797 Custom Widgets
1798 --------------
1800 When you start to write a lot of forms, you will probably find that you will
1801 reuse certain sets of widget attributes over and over again. Rather than
1802 repeat these attribute definitions every time you need them, Django allows
1803 you to capture those definitions as a custom widget.
1805 For example, if you find that you are including a lot of comment fields on forms,
1806 you could capture the idea of a ``TextInput`` with a specific ``size`` attribute
1807 as a custom extension to the ``TextInput`` widget::
1809     class CommentWidget(forms.TextInput):
1810         def __init__(self, *args, **kwargs):
1811             kwargs.setdefault('attrs',{}).update({'size': '40'})
1812             super(CommentWidget, self).__init__(*args, **kwargs)
1814 Then you can use this widget in your forms::
1816     class CommentForm(forms.Form):
1817         name = forms.CharField()
1818         url = forms.URLField()
1819         comment = forms.CharField(widget=CommentWidget)
1821 You can even customize your custom widget, in the same way as you would
1822 any other widget. Adding a once-off class to your ``CommentWidget`` is as
1823 simple as adding an attribute definition::
1825     class CommentForm(forms.Form):
1826         name = forms.CharField(max_length=20)
1827         url = forms.URLField()
1828         comment = forms.CharField(
1829                     widget=CommentWidget(attrs={'class': 'special'}))
1831 Django also makes it easy to specify a custom field type that uses your custom
1832 widget. For example, you could define a customized field type for comments
1833 by defining::
1835     class CommentInput(forms.CharField):
1836         widget = CommentWidget
1838 You can then use this field whenever you have a form that requires a comment::
1840     class CommentForm(forms.Form):
1841         name = forms.CharField()
1842         url = forms.URLField()
1843         comment = CommentInput()
1845 Generating forms for models
1846 ===========================
1848 The prefered way of generating forms that work with models is explained in the
1849 `ModelForms documentation`_.
1851 Looking for the ``form_for_model`` and ``form_for_instance`` documentation?
1852 They've been deprecated, but you can still `view the documentation`_.
1854 .. _ModelForms documentation: ../modelforms/
1855 .. _view the documentation: ../form_for_model/
1857 More coming soon
1858 ================
1860 That's all the documentation for now. For more, see the file
1861 http://code.djangoproject.com/browser/django/trunk/tests/regressiontests/forms
1862 -- the unit tests for ``django.newforms``. This can give you a good idea of
1863 what's possible. (Each submodule there contains separate tests.)
1865 If you're really itching to learn and use this library, please be patient.
1866 We're working hard on finishing both the code and documentation.