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.
12
``django.newforms`` currently is only available in Django beginning
13
with the 0.96 release. the Django development version -- i.e., it's
14
not available in the Django 0.95 release. For the next Django release,
15
our plan is to do the following:
17
* As of revision [4208], we've copied the current ``django.forms`` to
18
``django.oldforms``. This allows you to upgrade your code *now* rather
19
than waiting for the backwards-incompatible change and rushing to fix
20
your code after the fact. Just change your import statements like this::
22
from django import forms # old
23
from django import oldforms as forms # new
25
* At an undecided future date, we will move the current ``django.newforms``
26
to ``django.forms``. This will be a backwards-incompatible change, and
27
anybody who is still using the old version of ``django.forms`` at that
28
time will need to change their import statements, as described in the
31
* We will remove ``django.oldforms`` in the release *after* the next Django
32
release -- the release that comes after the release in which we're
33
creating the new ``django.forms``.
35
With this in mind, we recommend you use the following import statement when
36
using ``django.newforms``::
38
from django import newforms as forms
40
This way, your code can refer to the ``forms`` module, and when
41
``django.newforms`` is renamed to ``django.forms``, you'll only have to change
42
your ``import`` statements.
44
If you prefer "``import *``" syntax, you can do the following::
46
from django.newforms import *
48
This will import all fields, widgets, form classes and other various utilities
49
into your local namespace. Some people find this convenient; others find it
50
too messy. The choice is yours.
55
As with the ``django.forms`` ("manipulators") system before it,
56
``django.newforms`` is intended to handle HTML form display, data processing
57
(validation) and redisplay. It's what you use if you want to perform
58
server-side validation for an HTML form.
60
For example, if your Web site has a contact form that visitors can use to
61
send you e-mail, you'd use this library to implement the display of the HTML
62
form fields, along with the form validation. Any time you need to use an HTML
63
``<form>``, you can use this library.
65
The library deals with these concepts:
67
* **Widget** -- A class that corresponds to an HTML form widget, e.g.
68
``<input type="text">`` or ``<textarea>``. This handles rendering of the
71
* **Field** -- A class that is responsible for doing validation, e.g.
72
an ``EmailField`` that makes sure its data is a valid e-mail address.
74
* **Form** -- A collection of fields that knows how to validate itself and
75
display itself as HTML.
77
The library is decoupled from the other Django components, such as the database
78
layer, views and templates. It relies only on Django settings, a couple of
79
``django.utils`` helper functions and Django's internationalization hooks (but
80
you're not required to be using internationalization features to use this
86
The primary way of using the ``newforms`` library is to create a form object.
87
Do this by subclassing ``django.newforms.Form`` and specifying the form's
88
fields, in a declarative style that you'll be familiar with if you've used
89
Django database models. In this section, we'll iteratively develop a form
90
object that you might use to implement "contact me" functionality on your
93
Start with this basic ``Form`` subclass, which we'll call ``ContactForm``::
95
from django import newforms as forms
97
class ContactForm(forms.Form):
98
subject = forms.CharField(max_length=100)
99
message = forms.CharField()
100
sender = forms.EmailField()
101
cc_myself = forms.BooleanField()
103
A form is composed of ``Field`` objects. In this case, our form has four
104
fields: ``subject``, ``message``, ``sender`` and ``cc_myself``. We'll explain
105
the different types of fields -- e.g., ``CharField`` and ``EmailField`` --
108
Creating ``Form`` instances
109
---------------------------
111
A ``Form`` instance is either **bound** or **unbound** to a set of data.
113
* If it's **bound** to a set of data, it's capable of validating that data
114
and rendering the form as HTML with the data displayed in the HTML.
116
* If it's **unbound**, it cannot do validation (because there's no data to
117
validate!), but it can still render the blank form as HTML.
119
To create an unbound ``Form`` instance, simply instantiate the class::
121
>>> f = ContactForm()
123
To bind data to a form, pass the data as a dictionary as the first parameter to
124
your ``Form`` class constructor::
126
>>> data = {'subject': 'hello',
127
... 'message': 'Hi there',
128
... 'sender': 'foo@example.com',
129
... 'cc_myself': True}
130
>>> f = ContactForm(data)
132
In this dictionary, the keys are the field names, which correspond to the
133
attributes in your ``Form`` class. The values are the data you're trying
134
to validate. These will usually be strings, but there's no requirement that
135
they be strings; the type of data you pass depends on the ``Field``, as we'll
138
If you need to distinguish between bound and unbound form instances at runtime,
139
check the value of the form's ``is_bound`` attribute::
141
>>> f = ContactForm()
144
>>> f = ContactForm({'subject': 'hello'})
148
Note that passing an empty dictionary creates a *bound* form with empty data::
150
>>> f = ContactForm({})
154
If you have a bound ``Form`` instance and want to change the data somehow, or
155
if you want to bind an unbound ``Form`` instance to some data, create another
156
``Form`` instance. There is no way to change data in a ``Form`` instance. Once
157
a ``Form`` instance has been created, you should consider its data immutable,
158
whether it has data or not.
160
Using forms to validate data
161
----------------------------
163
The primary task of a ``Form`` object is to validate data. With a bound
164
``Form`` instance, call the ``is_valid()`` method to run validation and return
165
a boolean designating whether the data was valid::
167
>>> data = {'subject': 'hello',
168
... 'message': 'Hi there',
169
... 'sender': 'foo@example.com',
170
... 'cc_myself': True}
171
>>> f = ContactForm(data)
175
Let's try with some invalid data. In this case, ``subject`` is blank (an error,
176
because all fields are required by default) and ``sender`` is not a valid
179
>>> data = {'subject': '',
180
... 'message': 'Hi there',
181
... 'sender': 'invalid e-mail address',
182
... 'cc_myself': True}
183
>>> f = ContactForm(data)
187
Access the ``Form`` attribute ``errors`` to get a dictionary of error messages::
190
{'sender': [u'Enter a valid e-mail address.'], 'subject': [u'This field is required.']}
192
In this dictionary, the keys are the field names, and the values are lists of
193
Unicode strings representing the error messages. The error messages are stored
194
in lists because a field can have multiple error messages.
196
You can access ``errors`` without having to call ``is_valid()`` first. The
197
form's data will be validated the first time either you call ``is_valid()`` or
200
Behavior of unbound forms
201
~~~~~~~~~~~~~~~~~~~~~~~~~
203
It's meaningless to validate a form with no data, but, for the record, here's
204
what happens with unbound forms::
206
>>> f = ContactForm()
212
Accessing "clean" data
213
----------------------
215
Each ``Field`` in a ``Form`` class is responsible not only for validating data,
216
but also for "cleaning" it -- normalizing it to a consistent format. This is a
217
nice feature, because it allows data for a particular field to be input in
218
a variety of ways, always resulting in consistent output.
220
For example, ``DateField`` normalizes input into a Python ``datetime.date``
221
object. Regardless of whether you pass it a string in the format
222
``'1994-07-15'``, a ``datetime.date`` object or a number of other formats,
223
``DateField`` will always normalize it to a ``datetime.date`` object as long as
226
Once you've created a ``Form`` instance with a set of data and validated it,
227
you can access the clean data via the ``clean_data`` attribute of the ``Form``
230
>>> data = {'subject': 'hello',
231
... 'message': 'Hi there',
232
... 'sender': 'foo@example.com',
233
... 'cc_myself': True}
234
>>> f = ContactForm(data)
238
{'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'}
240
Note that any text-based field -- such as ``CharField`` or ``EmailField`` --
241
always cleans the input into a Unicode string. We'll cover the encoding
242
implications later in this document.
244
If your data does *not* validate, your ``Form`` instance will not have a
245
``clean_data`` attribute::
247
>>> data = {'subject': '',
248
... 'message': 'Hi there',
249
... 'sender': 'invalid e-mail address',
250
... 'cc_myself': True}
251
>>> f = ContactForm(data)
255
Traceback (most recent call last):
257
AttributeError: 'ContactForm' object has no attribute 'clean_data'
259
``clean_data`` will always *only* contain a key for fields defined in the
260
``Form``, even if you pass extra data when you define the ``Form``. In this
261
example, we pass a bunch of extra fields to the ``ContactForm`` constructor,
262
but ``clean_data`` contains only the form's fields::
264
>>> data = {'subject': 'hello',
265
... 'message': 'Hi there',
266
... 'sender': 'foo@example.com',
267
... 'cc_myself': True,
268
... 'extra_field_1': 'foo',
269
... 'extra_field_2': 'bar',
270
... 'extra_field_3': 'baz'}
271
>>> f = ContactForm(data)
274
>>> f.clean_data # Doesn't contain extra_field_1, etc.
275
{'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'}
277
Behavior of unbound forms
278
~~~~~~~~~~~~~~~~~~~~~~~~~
280
It's meaningless to request "clean" data in a form with no data, but, for the
281
record, here's what happens with unbound forms::
283
>>> f = ContactForm()
285
Traceback (most recent call last):
287
AttributeError: 'ContactForm' object has no attribute 'clean_data'
289
Outputting forms as HTML
290
------------------------
292
The second task of a ``Form`` object is to render itself as HTML. To do so,
293
simply ``print`` it::
295
>>> f = ContactForm()
297
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
298
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
299
<tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr>
300
<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>
302
If the form is bound to data, the HTML output will include that data
303
appropriately. For example, if a field is represented by an
304
``<input type="text">``, the data will be in the ``value`` attribute. If a
305
field is represented by an ``<input type="checkbox">``, then that HTML will
306
include ``checked="checked"`` if appropriate::
308
>>> data = {'subject': 'hello',
309
... 'message': 'Hi there',
310
... 'sender': 'foo@example.com',
311
... 'cc_myself': True}
312
>>> f = ContactForm(data)
314
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" value="hello" /></td></tr>
315
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" value="Hi there" /></td></tr>
316
<tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" value="foo@example.com" /></td></tr>
317
<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>
319
This default output is a two-column HTML table, with a ``<tr>`` for each field.
320
Notice the following:
322
* For flexibility, the output does *not* include the ``<table>`` and
323
``</table>`` tags, nor does it include the ``<form>`` and ``</form>``
324
tags or an ``<input type="submit">`` tag. It's your job to do that.
326
* Each field type has a default HTML representation. ``CharField`` and
327
``EmailField`` are represented by an ``<input type="text">``.
328
``BooleanField`` is represented by an ``<input type="checkbox">``. Note
329
these are merely sensible defaults; you can specify which HTML to use for
330
a given field by using widgets, which we'll explain shortly.
332
* The HTML ``name`` for each tag is taken directly from its attribute name
333
in the ``ContactForm`` class.
335
* The text label for each field -- e.g. ``'Subject:'``, ``'Message:'`` and
336
``'Cc myself:'`` is generated from the field name by converting all
337
underscores to spaces and upper-casing the first letter. Again, note
338
these are merely sensible defaults; you can also specify labels manually.
340
* Each text label is surrounded in an HTML ``<label>`` tag, which points
341
to the appropriate form field via its ``id``. Its ``id``, in turn, is
342
generated by prepending ``'id_'`` to the field name. The ``id``
343
attributes and ``<label>`` tags are included in the output by default, to
344
follow best practices, but you can change that behavior.
346
Although ``<table>`` output is the default output style when you ``print`` a
347
form, other output styles are available. Each style is available as a method on
348
a form object, and each rendering method returns a Unicode object.
353
``Form.as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>``
354
containing one field::
356
>>> f = ContactForm()
358
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>'
360
<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>
361
<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>
362
<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p>
363
<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>
368
``Form.as_ul()`` renders the form as a series of ``<li>`` tags, with each
369
``<li>`` containing one field. It does *not* include the ``<ul>`` or ``</ul>``,
370
so that you can specify any HTML attributes on the ``<ul>`` for flexibility::
372
>>> f = ContactForm()
374
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>'
376
<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>
377
<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>
378
<li><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></li>
379
<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>
384
Finally, ``Form.as_table()`` outputs the form as an HTML ``<table>``. This is
385
exactly the same as ``print``. In fact, when you ``print`` a form object, it
386
calls its ``as_table()`` method behind the scenes::
388
>>> f = ContactForm()
390
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>'
391
>>> print f.as_table()
392
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
393
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
394
<tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr>
395
<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>
397
Configuring HTML ``<label>`` tags
398
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
400
An HTML ``<label>`` tag designates which label text is associated with which
401
form element. This small enhancement makes forms more usable and more accessible
402
to assistive devices. It's always a good idea to use ``<label>`` tags.
404
By default, the form rendering methods include HTML ``id`` attributes on the
405
form elements and corresponding ``<label>`` tags around the labels. The ``id``
406
attribute values are generated by prepending ``id_`` to the form field names.
407
This behavior is configurable, though, if you want to change the ``id``
408
convention or remove HTML ``id`` attributes and ``<label>`` tags entirely.
410
Use the ``auto_id`` argument to the ``Form`` constructor to control the label
411
and ``id`` behavior. This argument must be ``True``, ``False`` or a string.
413
If ``auto_id`` is ``False``, then the form output will not include ``<label>``
414
tags nor ``id`` attributes::
416
>>> f = ContactForm(auto_id=False)
417
>>> print f.as_table()
418
<tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /></td></tr>
419
<tr><th>Message:</th><td><input type="text" name="message" /></td></tr>
420
<tr><th>Sender:</th><td><input type="text" name="sender" /></td></tr>
421
<tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr>
423
<li>Subject: <input type="text" name="subject" maxlength="100" /></li>
424
<li>Message: <input type="text" name="message" /></li>
425
<li>Sender: <input type="text" name="sender" /></li>
426
<li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
428
<p>Subject: <input type="text" name="subject" maxlength="100" /></p>
429
<p>Message: <input type="text" name="message" /></p>
430
<p>Sender: <input type="text" name="sender" /></p>
431
<p>Cc myself: <input type="checkbox" name="cc_myself" /></p>
433
If ``auto_id`` is set to ``True``, then the form output *will* include
434
``<label>`` tags and will simply use the field name as its ``id`` for each form
437
>>> f = ContactForm(auto_id=True)
438
>>> print f.as_table()
439
<tr><th><label for="subject">Subject:</label></th><td><input id="subject" type="text" name="subject" maxlength="100" /></td></tr>
440
<tr><th><label for="message">Message:</label></th><td><input type="text" name="message" id="message" /></td></tr>
441
<tr><th><label for="sender">Sender:</label></th><td><input type="text" name="sender" id="sender" /></td></tr>
442
<tr><th><label for="cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="cc_myself" /></td></tr>
444
<li><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></li>
445
<li><label for="message">Message:</label> <input type="text" name="message" id="message" /></li>
446
<li><label for="sender">Sender:</label> <input type="text" name="sender" id="sender" /></li>
447
<li><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></li>
449
<p><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></p>
450
<p><label for="message">Message:</label> <input type="text" name="message" id="message" /></p>
451
<p><label for="sender">Sender:</label> <input type="text" name="sender" id="sender" /></p>
452
<p><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></p>
454
If ``auto_id`` is set to a string containing the format character ``'%s'``,
455
then the form output will include ``<label>`` tags, and will generate ``id``
456
attributes based on the format string. For example, for a format string
457
``'field_%s'``, a field named ``subject`` will get the ``id``
458
``'field_subject'``. Continuing our example::
460
>>> f = ContactForm(auto_id='id_for_%s')
461
>>> print f.as_table()
462
<tr><th><label for="id_for_subject">Subject:</label></th><td><input id="id_for_subject" type="text" name="subject" maxlength="100" /></td></tr>
463
<tr><th><label for="id_for_message">Message:</label></th><td><input type="text" name="message" id="id_for_message" /></td></tr>
464
<tr><th><label for="id_for_sender">Sender:</label></th><td><input type="text" name="sender" id="id_for_sender" /></td></tr>
465
<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>
467
<li><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
468
<li><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></li>
469
<li><label for="id_for_sender">Sender:</label> <input type="text" name="sender" id="id_for_sender" /></li>
470
<li><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
472
<p><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></p>
473
<p><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></p>
474
<p><label for="id_for_sender">Sender:</label> <input type="text" name="sender" id="id_for_sender" /></p>
475
<p><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></p>
477
If ``auto_id`` is set to any other true value -- such as a string that doesn't
478
include ``%s`` -- then the library will act as if ``auto_id`` is ``True``.
480
By default, ``auto_id`` is set to the string ``'id_%s'``.
482
Notes on field ordering
483
~~~~~~~~~~~~~~~~~~~~~~~
485
In the ``as_p()``, ``as_ul()`` and ``as_table()`` shortcuts, the fields are
486
displayed in the order in which you define them in your form class. For
487
example, in the ``ContactForm`` example, the fields are defined in the order
488
``subject``, ``message``, ``sender``, ``cc_myself``. To reorder the HTML
489
output, just change the order in which those fields are listed in the class.
491
How errors are displayed
492
~~~~~~~~~~~~~~~~~~~~~~~~
494
If you render a bound ``Form`` object, the act of rendering will automatically
495
run the form's validation if it hasn't already happened, and the HTML output
496
will include the validation errors as a ``<ul>`` near the field. The particular
497
positioning of the error messages depends on the output method you're using::
499
>>> data = {'subject': '',
500
... 'message': 'Hi there',
501
... 'sender': 'invalid e-mail address',
502
... 'cc_myself': True}
503
>>> f = ContactForm(data, auto_id=False)
504
>>> print f.as_table()
505
<tr><th>Subject:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" /></td></tr>
506
<tr><th>Message:</th><td><input type="text" name="message" value="Hi there" /></td></tr>
507
<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>
508
<tr><th>Cc myself:</th><td><input checked="checked" type="checkbox" name="cc_myself" /></td></tr>
510
<li><ul class="errorlist"><li>This field is required.</li></ul>Subject: <input type="text" name="subject" maxlength="100" /></li>
511
<li>Message: <input type="text" name="message" value="Hi there" /></li>
512
<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>
513
<li>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></li>
515
<p><ul class="errorlist"><li>This field is required.</li></ul></p>
516
<p>Subject: <input type="text" name="subject" maxlength="100" /></p>
517
<p>Message: <input type="text" name="message" value="Hi there" /></p>
518
<p><ul class="errorlist"><li>Enter a valid e-mail address.</li></ul></p>
519
<p>Sender: <input type="text" name="sender" value="invalid e-mail address" /></p>
520
<p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p>
525
The ``as_p()``, ``as_ul()`` and ``as_table()`` methods are simply shortcuts for
526
lazy developers -- they're not the only way a form object can be displayed.
528
To display the HTML for a single field in your form, use dictionary lookup
529
syntax using the field's name as the key, and print the resulting object::
531
>>> f = ContactForm()
532
>>> print f['subject']
533
<input id="id_subject" type="text" name="subject" maxlength="100" />
534
>>> print f['message']
535
<input type="text" name="message" id="id_message" />
536
>>> print f['sender']
537
<input type="text" name="sender" id="id_sender" />
538
>>> print f['cc_myself']
539
<input type="checkbox" name="cc_myself" id="id_cc_myself" />
541
Call ``str()`` or ``unicode()`` on the field to get its rendered HTML as a
542
string or Unicode object, respectively::
544
>>> str(f['subject'])
545
'<input id="id_subject" type="text" name="subject" maxlength="100" />'
546
>>> unicode(f['subject'])
547
u'<input id="id_subject" type="text" name="subject" maxlength="100" />'
549
The field-specific output honors the form object's ``auto_id`` setting::
551
>>> f = ContactForm(auto_id=False)
552
>>> print f['message']
553
<input type="text" name="message" />
554
>>> f = ContactForm(auto_id='id_%s')
555
>>> print f['message']
556
<input type="text" name="message" id="id_message" />
558
For a field's list of errors, access the field's ``errors`` attribute. This
559
is a list-like object that is displayed as an HTML ``<ul>`` when printed::
561
>>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''}
562
>>> f = ContactForm(data, auto_id=False)
563
>>> print f['message']
564
<input type="text" name="message" />
565
>>> f['message'].errors
566
[u'This field is required.']
567
>>> print f['message'].errors
568
<ul class="errorlist"><li>This field is required.</li></ul>
569
>>> f['subject'].errors
571
>>> print f['subject'].errors
573
>>> str(f['subject'].errors)
579
If you subclass a custom ``Form`` class, the resulting ``Form`` class will
580
include all fields of the parent class(es), followed by the fields you define
583
In this example, ``ContactFormWithPriority`` contains all the fields from
584
``ContactForm``, plus an additional field, ``priority``. The ``ContactForm``
585
fields are ordered first::
587
>>> class ContactFormWithPriority(ContactForm):
588
... priority = forms.CharField()
589
>>> f = ContactFormWithPriority(auto_id=False)
591
<li>Subject: <input type="text" name="subject" maxlength="100" /></li>
592
<li>Message: <input type="text" name="message" /></li>
593
<li>Sender: <input type="text" name="sender" /></li>
594
<li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
595
<li>Priority: <input type="text" name="priority" /></li>
597
It's possible to subclass multiple forms, treating forms as "mix-ins." In this
598
example, ``BeatleForm`` subclasses both ``PersonForm`` and ``InstrumentForm``
599
(in that order), and its field list includes the fields from the parent
602
>>> class PersonForm(Form):
603
... first_name = CharField()
604
... last_name = CharField()
605
>>> class InstrumentForm(Form):
606
... instrument = CharField()
607
>>> class BeatleForm(PersonForm, InstrumentForm):
608
... haircut_type = CharField()
609
>>> b = BeatleForm(auto_id=False)
611
<li>First name: <input type="text" name="first_name" /></li>
612
<li>Last name: <input type="text" name="last_name" /></li>
613
<li>Instrument: <input type="text" name="instrument" /></li>
614
<li>Haircut type: <input type="text" name="haircut_type" /></li>
619
When you create a ``Form`` class, the most important part is defining the
620
fields of the form. Each field has custom validation logic, along with a few
623
Although the primary way you'll use ``Field`` classes is in ``Form`` classes,
624
you can also instantiate them and use them directly to get a better idea of
625
how they work. Each ``Field`` instance has a ``clean()`` method, which takes
626
a single argument and either raises a ``django.newforms.ValidationError``
627
exception or returns the clean value::
629
>>> f = forms.EmailField()
630
>>> f.clean('foo@example.com')
632
>>> f.clean(u'foo@example.com')
634
>>> f.clean('invalid e-mail address')
635
Traceback (most recent call last):
637
ValidationError: [u'Enter a valid e-mail address.']
639
If you've used Django's old forms/validation framework, take care in noticing
640
this ``ValidationError`` is different than the previous ``ValidationError``.
641
This one lives at ``django.newforms.ValidationError`` rather than
642
``django.core.validators.ValidationError``.
647
Each ``Field`` class constructor takes at least these arguments. Some
648
``Field`` classes take additional, field-specific arguments, but the following
649
should *always* be available:
654
By default, each ``Field`` class assumes the value is required, so if you pass
655
an empty value -- either ``None`` or the empty string (``""``) -- then
656
``clean()`` will raise a ``ValidationError`` exception::
658
>>> f = forms.CharField()
662
Traceback (most recent call last):
664
ValidationError: [u'This field is required.']
666
Traceback (most recent call last):
668
ValidationError: [u'This field is required.']
678
To specify that a field is *not* required, pass ``required=False`` to the
679
``Field`` constructor::
681
>>> f = forms.CharField(required=False)
695
If a ``Field`` has ``required=False`` and you pass ``clean()`` an empty value,
696
then ``clean()`` will return a *normalized* empty value rather than raising
697
``ValidationError``. For ``CharField``, this will be a Unicode empty string.
698
For other ``Field`` classes, it might be ``None``. (This varies from field to
704
The ``label`` argument lets you specify the "human-friendly" label for this
705
field. This is used when the ``Field`` is displayed in a ``Form``.
707
As explained in _`Outputting forms as HTML` above, the default label for a
708
``Field`` is generated from the field name by converting all underscores to
709
spaces and upper-casing the first letter. Specify ``label`` if that default
710
behavior doesn't result in an adequate label.
712
Here's a full example ``Form`` that implements ``label`` for two of its fields.
713
We've specified ``auto_id=False`` to simplify the output::
715
>>> class CommentForm(forms.Form):
716
... name = forms.CharField(label='Your name')
717
... url = forms.URLField(label='Your Web site', required=False)
718
... comment = forms.CharField()
719
>>> f = CommentForm(auto_id=False)
721
<tr><th>Your name:</th><td><input type="text" name="name" /></td></tr>
722
<tr><th>Your Web site:</th><td><input type="text" name="url" /></td></tr>
723
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
728
The ``initial`` argument lets you specify the initial value to use when
729
rendering this ``Field`` in an unbound ``Form``.
731
The use-case for this is when you want to display an "empty" form in which a
732
field is initialized to a particular value. For example::
734
>>> class CommentForm(forms.Form):
735
... name = forms.CharField(initial='Your name')
736
... url = forms.URLField(initial='http://')
737
... comment = forms.CharField()
738
>>> f = CommentForm(auto_id=False)
740
<tr><th>Name:</th><td><input type="text" name="name" value="Your name" /></td></tr>
741
<tr><th>Url:</th><td><input type="text" name="url" value="http://" /></td></tr>
742
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
744
You may be thinking, why not just pass a dictionary of the initial values as
745
data when displaying the form? Well, if you do that, you'll trigger validation,
746
and the HTML output will include any validation errors::
748
>>> class CommentForm(forms.Form):
749
... name = forms.CharField()
750
... url = forms.URLField()
751
... comment = forms.CharField()
752
>>> default_data = {'name': 'Your name', 'url': 'http://'}
753
>>> f = CommentForm(default_data, auto_id=False)
755
<tr><th>Name:</th><td><input type="text" name="name" value="Your name" /></td></tr>
756
<tr><th>Url:</th><td><ul class="errorlist"><li>Enter a valid URL.</li></ul><input type="text" name="url" value="http://" /></td></tr>
757
<tr><th>Comment:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="comment" /></td></tr>
759
This is why ``initial`` values are only displayed for unbound forms. For bound
760
forms, the HTML output will use the bound data.
762
Also note that ``initial`` values are *not* used as "fallback" data in
763
validation if a particular field's value is not given. ``initial`` values are
764
*only* intended for initial form display::
766
>>> class CommentForm(forms.Form):
767
... name = forms.CharField(initial='Your name')
768
... url = forms.URLField(initial='http://')
769
... comment = forms.CharField()
770
>>> data = {'name': '', 'url': '', 'comment': 'Foo'}
771
>>> f = CommentForm(data)
774
# The form does *not* fall back to using the initial values.
776
{'url': [u'This field is required.'], 'name': [u'This field is required.']}
781
The ``widget`` argument lets you specify a ``Widget`` class to use when
782
rendering this ``Field``. See _`Widgets` below for more information.
787
The ``help_text`` argument lets you specify descriptive text for this
788
``Field``. If you provide ``help_text``, it will be displayed next to the
789
``Field`` when the ``Field`` is rendered in a ``Form``.
791
Here's a full example ``Form`` that implements ``help_text`` for two of its
792
fields. We've specified ``auto_id=False`` to simplify the output::
794
>>> class HelpTextContactForm(forms.Form):
795
... subject = forms.CharField(max_length=100, help_text='100 characters max.')
796
... message = forms.CharField()
797
... sender = forms.EmailField(help_text='A valid e-mail address, please.')
798
... cc_myself = forms.BooleanField()
799
>>> f = HelpTextContactForm(auto_id=False)
800
>>> print f.as_table()
801
<tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /><br />100 characters max.</td></tr>
802
<tr><th>Message:</th><td><input type="text" name="message" /></td></tr>
803
<tr><th>Sender:</th><td><input type="text" name="sender" /><br />A valid e-mail address, please.</td></tr>
804
<tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr>
806
<li>Subject: <input type="text" name="subject" maxlength="100" /> 100 characters max.</li>
807
<li>Message: <input type="text" name="message" /></li>
808
<li>Sender: <input type="text" name="sender" /> A valid e-mail address, please.</li>
809
<li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
811
<p>Subject: <input type="text" name="subject" maxlength="100" /> 100 characters max.</p>
812
<p>Message: <input type="text" name="message" /></p>
813
<p>Sender: <input type="text" name="sender" /> A valid e-mail address, please.</p>
814
<p>Cc myself: <input type="checkbox" name="cc_myself" /></p>
816
Dynamic initial values
817
----------------------
819
The ``initial`` argument to ``Field`` (explained above) lets you hard-code the
820
initial value for a ``Field`` -- but what if you want to declare the initial
821
value at runtime? For example, you might want to fill in a ``username`` field
822
with the username of the current session.
824
To accomplish this, use the ``initial`` argument to a ``Form``. This argument,
825
if given, should be a dictionary mapping field names to initial values. Only
826
include the fields for which you're specifying an initial value; it's not
827
necessary to include every field in your form. For example::
829
>>> class CommentForm(forms.Form):
830
... name = forms.CharField()
831
... url = forms.URLField()
832
... comment = forms.CharField()
833
>>> f = CommentForm(initial={'name': 'your username'}, auto_id=False)
835
<tr><th>Name:</th><td><input type="text" name="name" value="your username" /></td></tr>
836
<tr><th>Url:</th><td><input type="text" name="url" /></td></tr>
837
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
838
>>> f = CommentForm(initial={'name': 'another username'}, auto_id=False)
840
<tr><th>Name:</th><td><input type="text" name="name" value="another username" /></td></tr>
841
<tr><th>Url:</th><td><input type="text" name="url" /></td></tr>
842
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
844
Just like the ``initial`` parameter to ``Field``, these values are only
845
displayed for unbound forms, and they're not used as fallback values if a
846
particular value isn't provided.
848
Finally, note that if a ``Field`` defines ``initial`` *and* you include
849
``initial`` when instantiating the ``Form``, then the latter ``initial`` will
850
have precedence. In this example, ``initial`` is provided both at the field
851
level and at the form instance level, and the latter gets precedence::
853
>>> class CommentForm(forms.Form):
854
... name = forms.CharField(initial='class')
855
... url = forms.URLField()
856
... comment = forms.CharField()
857
>>> f = CommentForm(initial={'name': 'instance'}, auto_id=False)
859
<tr><th>Name:</th><td><input type="text" name="name" value="instance" /></td></tr>
860
<tr><th>Url:</th><td><input type="text" name="url" /></td></tr>
861
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
866
That's all the documentation for now. For more, see the file
867
http://code.djangoproject.com/browser/django/trunk/tests/regressiontests/forms/tests.py
868
-- the unit tests for ``django.newforms``. This can give you a good idea of
871
If you're really itching to learn and use this library, please be patient.
872
We're working hard on finishing both the code and documentation.