| 1 |
==================== |
|---|
| 2 |
The newforms library |
|---|
| 3 |
==================== |
|---|
| 4 |
|
|---|
| 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. |
|---|
| 8 |
|
|---|
| 9 |
Migration plan |
|---|
| 10 |
============== |
|---|
| 11 |
|
|---|
| 12 |
``django.newforms`` currently is only available in the Django development version |
|---|
| 13 |
-- i.e., it's not available in the Django 0.95 release. For the next Django |
|---|
| 14 |
release, our plan is to do the following: |
|---|
| 15 |
|
|---|
| 16 |
* As of revision [4208], we've copied the current ``django.forms`` to |
|---|
| 17 |
``django.oldforms``. This allows you to upgrade your code *now* rather |
|---|
| 18 |
than waiting for the backwards-incompatible change and rushing to fix |
|---|
| 19 |
your code after the fact. Just change your import statements like this:: |
|---|
| 20 |
|
|---|
| 21 |
from django import forms # old |
|---|
| 22 |
from django import oldforms as forms # new |
|---|
| 23 |
|
|---|
| 24 |
* At an undecided future date, we will move the current ``django.newforms`` |
|---|
| 25 |
to ``django.forms``. This will be a backwards-incompatible change, and |
|---|
| 26 |
anybody who is still using the old version of ``django.forms`` at that |
|---|
| 27 |
time will need to change their import statements, as described in the |
|---|
| 28 |
previous bullet. |
|---|
| 29 |
|
|---|
| 30 |
* We will remove ``django.oldforms`` in the release *after* the next Django |
|---|
| 31 |
release -- the release that comes after the release in which we're |
|---|
| 32 |
creating the new ``django.forms``. |
|---|
| 33 |
|
|---|
| 34 |
With this in mind, we recommend you use the following import statement when |
|---|
| 35 |
using ``django.newforms``:: |
|---|
| 36 |
|
|---|
| 37 |
from django import newforms as forms |
|---|
| 38 |
|
|---|
| 39 |
This way, your code can refer to the ``forms`` module, and when |
|---|
| 40 |
``django.newforms`` is renamed to ``django.forms``, you'll only have to change |
|---|
| 41 |
your ``import`` statements. |
|---|
| 42 |
|
|---|
| 43 |
If you prefer "``import *``" syntax, you can do the following:: |
|---|
| 44 |
|
|---|
| 45 |
from django.newforms import * |
|---|
| 46 |
|
|---|
| 47 |
This will import all fields, widgets, form classes and other various utilities |
|---|
| 48 |
into your local namespace. Some people find this convenient; others find it |
|---|
| 49 |
too messy. The choice is yours. |
|---|
| 50 |
|
|---|
| 51 |
Overview |
|---|
| 52 |
======== |
|---|
| 53 |
|
|---|
| 54 |
As the ``django.forms`` ("manipulators") system before it, ``django.newforms`` |
|---|
| 55 |
is intended to handle HTML form display, validation and redisplay. It's what |
|---|
| 56 |
you use if you want to perform server-side validation for an HTML form. |
|---|
| 57 |
|
|---|
| 58 |
For example, if your Web site has a contact form that visitors can use to |
|---|
| 59 |
send you e-mail, you'd use this library to implement the display of the HTML |
|---|
| 60 |
form fields, along with the form validation. Any time you need to use an HTML |
|---|
| 61 |
``<form>``, you can use this library. |
|---|
| 62 |
|
|---|
| 63 |
The library deals with these concepts: |
|---|
| 64 |
|
|---|
| 65 |
* **Widget** -- A class that corresponds to an HTML form widget, e.g. |
|---|
| 66 |
``<input type="text">`` or ``<textarea>``. This handles rendering of the |
|---|
| 67 |
widget as HTML. |
|---|
| 68 |
|
|---|
| 69 |
* **Field** -- A class that is responsible for doing validation, e.g. |
|---|
| 70 |
an ``EmailField`` that makes sure its data is a valid e-mail address. |
|---|
| 71 |
|
|---|
| 72 |
* **Form** -- A collection of fields that knows how to validate itself and |
|---|
| 73 |
display itself as HTML. |
|---|
| 74 |
|
|---|
| 75 |
The library is decoupled from the other Django components, such as the database |
|---|
| 76 |
layer, views and templates. It relies only on Django settings, a couple of |
|---|
| 77 |
``django.utils`` helper functions and Django's internationalization hooks (but |
|---|
| 78 |
you're not required to be using internationalization features to use this |
|---|
| 79 |
library). |
|---|
| 80 |
|
|---|
| 81 |
Form objects |
|---|
| 82 |
============ |
|---|
| 83 |
|
|---|
| 84 |
The primary way of using the ``newforms`` library is to create a form object. |
|---|
| 85 |
Do this by subclassing ``django.newforms.Form`` and specifying the form's |
|---|
| 86 |
fields, in a declarative style that you'll be familiar with if you've used |
|---|
| 87 |
Django database models. In this section, we'll iteratively develop a form |
|---|
| 88 |
object that you might use to implement "contact me" functionality on your |
|---|
| 89 |
personal Web site. |
|---|
| 90 |
|
|---|
| 91 |
Start with this basic ``Form`` subclass, which we'll call ``ContactForm``:: |
|---|
| 92 |
|
|---|
| 93 |
from django import newforms as forms |
|---|
| 94 |
|
|---|
| 95 |
class ContactForm(forms.Form): |
|---|
| 96 |
subject = forms.CharField(max_length=100) |
|---|
| 97 |
message = forms.CharField() |
|---|
| 98 |
sender = forms.EmailField() |
|---|
| 99 |
cc_myself = forms.BooleanField() |
|---|
| 100 |
|
|---|
| 101 |
A form is composed of ``Field`` objects. In this case, our form has four |
|---|
| 102 |
fields: ``subject``, ``message``, ``sender`` and ``cc_myself``. We'll explain |
|---|
| 103 |
the different types of fields -- e.g., ``CharField`` and ``EmailField`` -- |
|---|
| 104 |
shortly. |
|---|
| 105 |
|
|---|
| 106 |
Creating ``Form`` instances |
|---|
| 107 |
--------------------------- |
|---|
| 108 |
|
|---|
| 109 |
A ``Form`` instance is either **bound** or **unbound** to a set of data. |
|---|
| 110 |
|
|---|
| 111 |
* If it's **bound** to a set of data, it's capable of validating that data |
|---|
| 112 |
and rendering the form as HTML with the data displayed in the HTML. |
|---|
| 113 |
|
|---|
| 114 |
* If it's **unbound**, it cannot do validation (because there's no data to |
|---|
| 115 |
validate!), but it can still render the blank form as HTML. |
|---|
| 116 |
|
|---|
| 117 |
To create an unbound ``Form`` instance, simply instantiate the class:: |
|---|
| 118 |
|
|---|
| 119 |
>>> f = ContactForm() |
|---|
| 120 |
|
|---|
| 121 |
To bind data to a form, pass the data as a dictionary as the first parameter to |
|---|
| 122 |
your ``Form`` class constructor:: |
|---|
| 123 |
|
|---|
| 124 |
>>> data = {'subject': 'hello', |
|---|
| 125 |
... 'message': 'Hi there', |
|---|
| 126 |
... 'sender': 'foo@example.com', |
|---|
| 127 |
... 'cc_myself': True} |
|---|
| 128 |
>>> f = ContactForm(data) |
|---|
| 129 |
|
|---|
| 130 |
In this dictionary, the keys are the field names, which correspond to the |
|---|
| 131 |
attributes in your ``Form`` class. The values are the data you're trying |
|---|
| 132 |
to validate. These will usually be strings, but there's no requirement that |
|---|
| 133 |
they be strings; the type of data you pass depends on the ``Field``, as we'll |
|---|
| 134 |
see in a moment. |
|---|
| 135 |
|
|---|
| 136 |
If you need to distinguish between bound and unbound form instances at runtime, |
|---|
| 137 |
check the value of the form's ``is_bound`` attribute:: |
|---|
| 138 |
|
|---|
| 139 |
>>> f = ContactForm() |
|---|
| 140 |
>>> f.is_bound |
|---|
| 141 |
False |
|---|
| 142 |
>>> f = ContactForm({'subject': 'hello'}) |
|---|
| 143 |
>>> f.is_bound |
|---|
| 144 |
True |
|---|
| 145 |
|
|---|
| 146 |
Note that passing an empty dictionary creates a *bound* form with empty data:: |
|---|
| 147 |
|
|---|
| 148 |
>>> f = ContactForm({}) |
|---|
| 149 |
>>> f.is_bound |
|---|
| 150 |
True |
|---|
| 151 |
|
|---|
| 152 |
If you have a bound ``Form`` instance and want to change the data somehow, or |
|---|
| 153 |
if you want to bind an unbound ``Form`` instance to some data, create another |
|---|
| 154 |
``Form`` instance. There is no way to change data in a ``Form`` instance. Once |
|---|
| 155 |
a ``Form`` instance has been created, you should consider its data immutable, |
|---|
| 156 |
whether it has data or not. |
|---|
| 157 |
|
|---|
| 158 |
Using forms to validate data |
|---|
| 159 |
---------------------------- |
|---|
| 160 |
|
|---|
| 161 |
The primary task of a ``Form`` object is to validate data. With a bound |
|---|
| 162 |
``Form`` instance, call the ``is_valid()`` method to run validation and return |
|---|
| 163 |
a boolean designating whether the data was valid:: |
|---|
| 164 |
|
|---|
| 165 |
>>> data = {'subject': 'hello', |
|---|
| 166 |
... 'message': 'Hi there', |
|---|
| 167 |
... 'sender': 'foo@example.com', |
|---|
| 168 |
... 'cc_myself': True} |
|---|
| 169 |
>>> f = ContactForm(data) |
|---|
| 170 |
>>> f.is_valid() |
|---|
| 171 |
True |
|---|
| 172 |
|
|---|
| 173 |
Let's try with some invalid data. In this case, ``subject`` is blank (an error, |
|---|
| 174 |
because all fields are required by default) and ``sender`` is not a valid |
|---|
| 175 |
e-mail address:: |
|---|
| 176 |
|
|---|
| 177 |
>>> data = {'subject': '', |
|---|
| 178 |
... 'message': 'Hi there', |
|---|
| 179 |
... 'sender': 'invalid e-mail address', |
|---|
| 180 |
... 'cc_myself': True} |
|---|
| 181 |
>>> f = ContactForm(data) |
|---|
| 182 |
>>> f.is_valid() |
|---|
| 183 |
False |
|---|
| 184 |
|
|---|
| 185 |
Access the ``Form`` attribute ``errors`` to get a dictionary of error messages:: |
|---|
| 186 |
|
|---|
| 187 |
>>> f.errors |
|---|
| 188 |
{'sender': [u'Enter a valid e-mail address.'], 'subject': [u'This field is required.']} |
|---|
| 189 |
|
|---|
| 190 |
In this dictionary, the keys are the field names, and the values are lists of |
|---|
| 191 |
Unicode strings representing the error messages. The error messages are stored |
|---|
| 192 |
in lists because a field can have multiple error messages. |
|---|
| 193 |
|
|---|
| 194 |
You can access ``errors`` without having to call ``is_valid()`` first. The |
|---|
| 195 |
form's data will be validated the first time either you call ``is_valid()`` or |
|---|
| 196 |
access ``errors``. |
|---|
| 197 |
|
|---|
| 198 |
Behavior of unbound forms |
|---|
| 199 |
~~~~~~~~~~~~~~~~~~~~~~~~~ |
|---|
| 200 |
|
|---|
| 201 |
It's meaningless to validate a form with no data, but, for the record, here's |
|---|
| 202 |
what happens with unbound forms:: |
|---|
| 203 |
|
|---|
| 204 |
>>> f = ContactForm() |
|---|
| 205 |
>>> f.is_valid() |
|---|
| 206 |
False |
|---|
| 207 |
>>> f.errors |
|---|
| 208 |
{} |
|---|
| 209 |
|
|---|
| 210 |
Accessing "clean" data |
|---|
| 211 |
---------------------- |
|---|
| 212 |
|
|---|
| 213 |
Each ``Field`` in a ``Form`` class is responsible not only for validating data, |
|---|
| 214 |
but also for "cleaning" it -- normalizing it to a consistent format. This is a |
|---|
| 215 |
nice feature, because it allows data for a particular field to be input in |
|---|
| 216 |
a variety of ways, always resulting in consistent output. |
|---|
| 217 |
|
|---|
| 218 |
For example, ``DateField`` normalizes input into a Python ``datetime.date`` |
|---|
| 219 |
object. Regardless of whether you pass it a string in the format |
|---|
| 220 |
``'1994-07-15'``, a ``datetime.date`` object or a number of other formats, |
|---|
| 221 |
``DateField`` will always normalize it to a ``datetime.date`` object as long as |
|---|
| 222 |
it's valid. |
|---|
| 223 |
|
|---|
| 224 |
Once you've created a ``Form`` instance with a set of data and validated it, |
|---|
| 225 |
you can access the clean data via the ``clean_data`` attribute of the ``Form`` |
|---|
| 226 |
object:: |
|---|
| 227 |
|
|---|
| 228 |
>>> data = {'subject': 'hello', |
|---|
| 229 |
... 'message': 'Hi there', |
|---|
| 230 |
... 'sender': 'foo@example.com', |
|---|
| 231 |
... 'cc_myself': True} |
|---|
| 232 |
>>> f = ContactForm(data) |
|---|
| 233 |
>>> f.is_valid() |
|---|
| 234 |
True |
|---|
| 235 |
>>> f.clean_data |
|---|
| 236 |
{'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'} |
|---|
| 237 |
|
|---|
| 238 |
Note that any text-based field -- such as ``CharField`` or ``EmailField`` -- |
|---|
| 239 |
always cleans the input into a Unicode string. We'll cover the encoding |
|---|
| 240 |
implications later in this document. |
|---|
| 241 |
|
|---|
| 242 |
If your data does *not* validate, your ``Form`` instance will not have a |
|---|
| 243 |
``clean_data`` attribute:: |
|---|
| 244 |
|
|---|
| 245 |
>>> data = {'subject': '', |
|---|
| 246 |
... 'message': 'Hi there', |
|---|
| 247 |
... 'sender': 'invalid e-mail address', |
|---|
| 248 |
... 'cc_myself': True} |
|---|
| 249 |
>>> f = ContactForm(data) |
|---|
| 250 |
>>> f.is_valid() |
|---|
| 251 |
False |
|---|
| 252 |
>>> f.clean_data |
|---|
| 253 |
Traceback (most recent call last): |
|---|
| 254 |
... |
|---|
| 255 |
AttributeError: 'ContactForm' object has no attribute 'clean_data' |
|---|
| 256 |
|
|---|
| 257 |
``clean_data`` will always *only* contain a key for fields defined in the |
|---|
| 258 |
``Form``, even if you pass extra data when you define the ``Form``. In this |
|---|
| 259 |
example, we pass a bunch of extra fields to the ``ContactForm`` constructor, |
|---|
| 260 |
but ``clean_data`` contains only the form's fields:: |
|---|
| 261 |
|
|---|
| 262 |
>>> data = {'subject': 'hello', |
|---|
| 263 |
... 'message': 'Hi there', |
|---|
| 264 |
... 'sender': 'foo@example.com', |
|---|
| 265 |
... 'cc_myself': True, |
|---|
| 266 |
... 'extra_field_1': 'foo', |
|---|
| 267 |
... 'extra_field_2': 'bar', |
|---|
| 268 |
... 'extra_field_3': 'baz'} |
|---|
| 269 |
>>> f = ContactForm(data) |
|---|
| 270 |
>>> f.is_valid() |
|---|
| 271 |
True |
|---|
| 272 |
>>> f.clean_data # Doesn't contain extra_field_1, etc. |
|---|
| 273 |
{'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'} |
|---|
| 274 |
|
|---|
| 275 |
Behavior of unbound forms |
|---|
| 276 |
~~~~~~~~~~~~~~~~~~~~~~~~~ |
|---|
| 277 |
|
|---|
| 278 |
It's meaningless to request "clean" data in a form with no data, but, for the |
|---|
| 279 |
record, here's what happens with unbound forms:: |
|---|
| 280 |
|
|---|
| 281 |
>>> f = ContactForm() |
|---|
| 282 |
>>> f.clean_data |
|---|
| 283 |
Traceback (most recent call last): |
|---|
| 284 |
... |
|---|
| 285 |
AttributeError: 'ContactForm' object has no attribute 'clean_data' |
|---|
| 286 |
|
|---|
| 287 |
Outputting forms as HTML |
|---|
| 288 |
------------------------ |
|---|
| 289 |
|
|---|
| 290 |
The second task of a ``Form`` object is to render itself as HTML. To do so, |
|---|
| 291 |
simply ``print`` it:: |
|---|
| 292 |
|
|---|
| 293 |
>>> f = ContactForm() |
|---|
| 294 |
>>> print f |
|---|
| 295 |
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr> |
|---|
| 296 |
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr> |
|---|
| 297 |
<tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr> |
|---|
| 298 |
<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr> |
|---|
| 299 |
|
|---|
| 300 |
If the form is bound to data, the HTML output will include that data |
|---|
| 301 |
appropriately. For example, if a field is represented by an |
|---|
| 302 |
``<input type="text">``, the data will be in the ``value`` attribute. If a |
|---|
| 303 |
field is represented by an ``<input type="checkbox">``, then that HTML will |
|---|
| 304 |
include ``checked="checked"`` if appropriate:: |
|---|
| 305 |
|
|---|
| 306 |
>>> data = {'subject': 'hello', |
|---|
| 307 |
... 'message': 'Hi there', |
|---|
| 308 |
... 'sender': 'foo@example.com', |
|---|
| 309 |
... 'cc_myself': True} |
|---|
| 310 |
>>> f = ContactForm(data) |
|---|
| 311 |
>>> print f |
|---|
| 312 |
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" value="hello" /></td></tr> |
|---|
| 313 |
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" value="Hi there" /></td></tr> |
|---|
| 314 |
<tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" value="foo@example.com" /></td></tr> |
|---|
| 315 |
<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> |
|---|
| 316 |
|
|---|
| 317 |
This default output is a two-column HTML table, with a ``<tr>`` for each field. |
|---|
| 318 |
Notice the following: |
|---|
| 319 |
|
|---|
| 320 |
* For flexibility, the output does *not* include the ``<table>`` and |
|---|
| 321 |
``</table>`` tags, nor does it include the ``<form>`` and ``</form>`` |
|---|
| 322 |
tags or an ``<input type="submit">`` tag. It's your job to do that. |
|---|
| 323 |
|
|---|
| 324 |
* Each field type has a default HTML representation. ``CharField`` and |
|---|
| 325 |
``EmailField`` are represented by an ``<input type="text">``. |
|---|
| 326 |
``BooleanField`` is represented by an ``<input type="checkbox">``. Note |
|---|
| 327 |
these are merely sensible defaults; you can specify which HTML to use for |
|---|
| 328 |
a given field by using widgets, which we'll explain shortly. |
|---|
| 329 |
|
|---|
| 330 |
* The HTML ``name`` for each tag is taken directly from its attribute name |
|---|
| 331 |
in the ``ContactForm`` class. |
|---|
| 332 |
|
|---|
| 333 |
* The text label for each field -- e.g. ``'Subject:'``, ``'Message:'`` and |
|---|
| 334 |
``'Cc myself:'`` is generated from the field name by converting all |
|---|
| 335 |
underscores to spaces and upper-casing the first letter. Again, note |
|---|
| 336 |
these are merely sensible defaults; you can also specify labels manually. |
|---|
| 337 |
|
|---|
| 338 |
* Each text label is surrounded in an HTML ``<label>`` tag, which points |
|---|
| 339 |
to the appropriate form field via its ``id``. Its ``id``, in turn, is |
|---|
| 340 |
generated by prepending ``'id_'`` to the field name. The ``id`` |
|---|
| 341 |
attributes and ``<label>`` tags are included in the output by default, to |
|---|
| 342 |
follow best practices, but you can change that behavior. |
|---|
| 343 |
|
|---|
| 344 |
Although ``<table>`` output is the default output style when you ``print`` a |
|---|
| 345 |
form, other output styles are available. Each style is available as a method on |
|---|
| 346 |
a form object, and each rendering method returns a Unicode object. |
|---|
| 347 |
|
|---|
| 348 |
``as_p()`` |
|---|
| 349 |
~~~~~~~~~~ |
|---|
| 350 |
|
|---|
| 351 |
``Form.as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>`` |
|---|
| 352 |
containing one field:: |
|---|
| 353 |
|
|---|
| 354 |
>>> f = ContactForm() |
|---|
| 355 |
>>> f.as_p() |
|---|
| 356 |
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>' |
|---|
| 357 |
>>> print f.as_p() |
|---|
| 358 |
<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p> |
|---|
| 359 |
<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p> |
|---|
| 360 |
<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p> |
|---|
| 361 |
<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p> |
|---|
| 362 |
|
|---|
| 363 |
``as_ul()`` |
|---|
| 364 |
~~~~~~~~~~~ |
|---|
| 365 |
|
|---|
| 366 |
``Form.as_ul()`` renders the form as a series of ``<li>`` tags, with each |
|---|
| 367 |
``<li>`` containing one field. It does *not* include the ``<ul>`` or ``</ul>``, |
|---|
| 368 |
so that you can specify any HTML attributes on the ``<ul>`` for flexibility:: |
|---|
| 369 |
|
|---|
| 370 |
>>> f = ContactForm() |
|---|
| 371 |
>>> f.as_ul() |
|---|
| 372 |
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>' |
|---|
| 373 |
>>> print f.as_ul() |
|---|
| 374 |
<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li> |
|---|
| 375 |
<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li> |
|---|
| 376 |
<li><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></li> |
|---|
| 377 |
<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li> |
|---|
| 378 |
|
|---|
| 379 |
``as_table()`` |
|---|
| 380 |
~~~~~~~~~~~~~~ |
|---|
| 381 |
|
|---|
| 382 |
Finally, ``Form.as_table()`` outputs the form as an HTML ``<table>``. This is |
|---|
| 383 |
exactly the same as ``print``. In fact, when you ``print`` a form object, it |
|---|
| 384 |
calls its ``as_table()`` method behind the scenes:: |
|---|
| 385 |
|
|---|
| 386 |
>>> f = ContactForm() |
|---|
| 387 |
>>> f.as_table() |
|---|
| 388 |
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>' |
|---|
| 389 |
>>> print f.as_table() |
|---|
| 390 |
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr> |
|---|
| 391 |
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr> |
|---|
| 392 |
<tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr> |
|---|
| 393 |
<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr> |
|---|
| 394 |
|
|---|
| 395 |
Configuring HTML ``<label>`` tags |
|---|
| 396 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|---|
| 397 |
|
|---|
| 398 |
An HTML ``<label>`` tag designates which label text is associated with which |
|---|
| 399 |
form element. This small enhancement makes forms more usable and more accessible |
|---|
| 400 |
to assistive devices. It's always a good idea to use ``<label>`` tags. |
|---|
| 401 |
|
|---|
| 402 |
By default, the form rendering methods include HTML ``id`` attributes on the |
|---|
| 403 |
form elements and corresponding ``<label>`` tags around the labels. The ``id`` |
|---|
| 404 |
attribute values are generated by prepending ``id_`` to the form field names. |
|---|
| 405 |
This behavior is configurable, though, if you want to change the ``id`` |
|---|
| 406 |
convention or remove HTML ``id`` attributes and ``<label>`` tags entirely. |
|---|
| 407 |
|
|---|
| 408 |
Use the ``auto_id`` argument to the ``Form`` constructor to control the label |
|---|
| 409 |
and ``id`` behavior. This argument must be ``True``, ``False`` or a string. |
|---|
| 410 |
|
|---|
| 411 |
If ``auto_id`` is ``False``, then the form output will not include ``<label>`` |
|---|
| 412 |
tags nor ``id`` attributes:: |
|---|
| 413 |
|
|---|
| 414 |
>>> f = ContactForm(auto_id=False) |
|---|
| 415 |
>>> print f.as_table() |
|---|
| 416 |
<tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /></td></tr> |
|---|
| 417 |
<tr><th>Message:</th><td><input type="text" name="message" /></td></tr> |
|---|
| 418 |
<tr><th>Sender:</th><td><input type="text" name="sender" /></td></tr> |
|---|
| 419 |
<tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr> |
|---|
| 420 |
>>> print f.as_ul() |
|---|
| 421 |
<li>Subject: <input type="text" name="subject" maxlength="100" /></li> |
|---|
| 422 |
<li>Message: <input type="text" name="message" /></li> |
|---|
| 423 |
<li>Sender: <input type="text" name="sender" /></li> |
|---|
| 424 |
<li>Cc myself: <input type="checkbox" name="cc_myself" /></li> |
|---|
| 425 |
>>> print f.as_p() |
|---|
| 426 |
<p>Subject: <input type="text" name="subject" maxlength="100" /></p> |
|---|
| 427 |
<p>Message: <input type="text" name="message" /></p> |
|---|
| 428 |
<p>Sender: <input type="text" name="sender" /></p> |
|---|
| 429 |
<p>Cc myself: <input type="checkbox" name="cc_myself" /></p> |
|---|
| 430 |
|
|---|
| 431 |
If ``auto_id`` is set to ``True``, then the form output *will* include |
|---|
| 432 |
``<label>`` tags and will simply use the field name as its ``id`` for each form |
|---|
| 433 |
field:: |
|---|
| 434 |
|
|---|
| 435 |
>>> f = ContactForm(auto_id=True) |
|---|
| 436 |
>>> print f.as_table() |
|---|
| 437 |
<tr><th><label for="subject">Subject:</label></th><td><input id="subject" type="text" name="subject" maxlength="100" /></td></tr> |
|---|
| 438 |
<tr><th><label for="message">Message:</label></th><td><input type="text" name="message" id="message" /></td></tr> |
|---|
| 439 |
<tr><th><label for="sender">Sender:</label></th><td><input type="text" name="sender" id="sender" /></td></tr> |
|---|
| 440 |
<tr><th><label for="cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="cc_myself" /></td></tr> |
|---|
| 441 |
>>> print f.as_ul() |
|---|
| 442 |
<li><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></li> |
|---|
| 443 |
<li><label for="message">Message:</label> <input type="text" name="message" id="message" /></li> |
|---|
| 444 |
<li><label for="sender">Sender:</label> <input type="text" name="sender" id="sender" /></li> |
|---|
| 445 |
<li><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></li> |
|---|
| 446 |
>>> print f.as_p() |
|---|
| 447 |
<p><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></p> |
|---|
| 448 |
<p><label for="message">Message:</label> <input type="text" name="message" id="message" /></p> |
|---|
| 449 |
<p><label for="sender">Sender:</label> <input type="text" name="sender" id="sender" /></p> |
|---|
| 450 |
<p><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></p> |
|---|
| 451 |
|
|---|
| 452 |
If ``auto_id`` is set to a string containing the format character ``'%s'``, |
|---|
| 453 |
then the form output will include ``<label>`` tags, and will generate ``id`` |
|---|
| 454 |
attributes based on the format string. For example, for a format string |
|---|
| 455 |
``'field_%s'``, a field named ``subject`` will get the ``id`` |
|---|
| 456 |
``'field_subject'``. Continuing our example:: |
|---|
| 457 |
|
|---|
| 458 |
>>> f = ContactForm(auto_id='id_for_%s') |
|---|
| 459 |
>>> print f.as_table() |
|---|
| 460 |
<tr><th><label for="id_for_subject">Subject:</label></th><td><input id="id_for_subject" type="text" name="subject" maxlength="100" /></td></tr> |
|---|
| 461 |
<tr><th><label for="id_for_message">Message:</label></th><td><input type="text" name="message" id="id_for_message" /></td></tr> |
|---|
| 462 |
<tr><th><label for="id_for_sender">Sender:</label></th><td><input type="text" name="sender" id="id_for_sender" /></td></tr> |
|---|
| 463 |
<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> |
|---|
| 464 |
>>> print f.as_ul() |
|---|
| 465 |
<li><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li> |
|---|
| 466 |
<li><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></li> |
|---|
| 467 |
<li><label for="id_for_sender">Sender:</label> <input type="text" name="sender" id="id_for_sender" /></li> |
|---|
| 468 |
<li><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li> |
|---|
| 469 |
>>> print f.as_p() |
|---|
| 470 |
<p><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></p> |
|---|
| 471 |
<p><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></p> |
|---|
| 472 |
<p><label for="id_for_sender">Sender:</label> <input type="text" name="sender" id="id_for_sender" /></p> |
|---|
| 473 |
<p><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></p> |
|---|
| 474 |
|
|---|
| 475 |
If ``auto_id`` is set to any other true value -- such as a string that doesn't |
|---|
| 476 |
include ``%s`` -- then the library will act as if ``auto_id`` is ``True``. |
|---|
| 477 |
|
|---|
| 478 |
By default, ``auto_id`` is set to the string ``'id_%s'``. |
|---|
| 479 |
|
|---|
| 480 |
Notes on field ordering |
|---|
| 481 |
~~~~~~~~~~~~~~~~~~~~~~~ |
|---|
| 482 |
|
|---|
| 483 |
In the ``as_p()``, ``as_ul()`` and ``as_table()`` shortcuts, the fields are |
|---|
| 484 |
displayed in the order in which you define them in your form class. For |
|---|
| 485 |
example, in the ``ContactForm`` example, the fields are defined in the order |
|---|
| 486 |
``subject``, ``message``, ``sender``, ``cc_myself``. To reorder the HTML |
|---|
| 487 |
output, just change the order in which those fields are listed in the class. |
|---|
| 488 |
|
|---|
| 489 |
How errors are displayed |
|---|
| 490 |
~~~~~~~~~~~~~~~~~~~~~~~~ |
|---|
| 491 |
|
|---|
| 492 |
If you render a bound ``Form`` object, the act of rendering will automatically |
|---|
| 493 |
run the form's validation if it hasn't already happened, and the HTML output |
|---|
| 494 |
will include the validation errors as a ``<ul>`` near the field. The particular |
|---|
| 495 |
positioning of the error messages depends on the output method you're using:: |
|---|
| 496 |
|
|---|
| 497 |
>>> data = {'subject': '', |
|---|
| 498 |
... 'message': 'Hi there', |
|---|
| 499 |
... 'sender': 'invalid e-mail address', |
|---|
| 500 |
... 'cc_myself': True} |
|---|
| 501 |
>>> f = ContactForm(data, auto_id=False) |
|---|
| 502 |
>>> print f.as_table() |
|---|
| 503 |
<tr><th>Subject:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" /></td></tr> |
|---|
| 504 |
<tr><th>Message:</th><td><input type="text" name="message" value="Hi there" /></td></tr> |
|---|
| 505 |
<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> |
|---|
| 506 |
<tr><th>Cc myself:</th><td><input checked="checked" type="checkbox" name="cc_myself" /></td></tr> |
|---|
| 507 |
>>> print f.as_ul() |
|---|
| 508 |
<li><ul class="errorlist"><li>This field is required.</li></ul>Subject: <input type="text" name="subject" maxlength="100" /></li> |
|---|
| 509 |
<li>Message: <input type="text" name="message" value="Hi there" /></li> |
|---|
| 510 |
<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> |
|---|
| 511 |
<li>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></li> |
|---|
| 512 |
>>> print f.as_p() |
|---|
| 513 |
<p><ul class="errorlist"><li>This field is required.</li></ul></p> |
|---|
| 514 |
<p>Subject: <input type="text" name="subject" maxlength="100" /></p> |
|---|
| 515 |
<p>Message: <input type="text" name="message" value="Hi there" /></p> |
|---|
| 516 |
<p><ul class="errorlist"><li>Enter a valid e-mail address.</li></ul></p> |
|---|
| 517 |
<p>Sender: <input type="text" name="sender" value="invalid e-mail address" /></p> |
|---|
| 518 |
<p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p> |
|---|
| 519 |
|
|---|
| 520 |
More granular output |
|---|
| 521 |
~~~~~~~~~~~~~~~~~~~~ |
|---|
| 522 |
|
|---|
| 523 |
The ``as_p()``, ``as_ul()`` and ``as_table()`` methods are simply shortcuts for |
|---|
| 524 |
lazy developers -- they're not the only way a form object can be displayed. |
|---|
| 525 |
|
|---|
| 526 |
To display the HTML for a single field in your form, use dictionary lookup |
|---|
| 527 |
syntax using the field's name as the key, and print the resulting object:: |
|---|
| 528 |
|
|---|
| 529 |
>>> f = ContactForm() |
|---|
| 530 |
>>> print f['subject'] |
|---|
| 531 |
<input id="id_subject" type="text" name="subject" maxlength="100" /> |
|---|
| 532 |
>>> print f['message'] |
|---|
| 533 |
<input type="text" name="message" id="id_message" /> |
|---|
| 534 |
>>> print f['sender'] |
|---|
| 535 |
<input type="text" name="sender" id="id_sender" /> |
|---|
| 536 |
>>> print f['cc_myself'] |
|---|
| 537 |
<input type="checkbox" name="cc_myself" id="id_cc_myself" /> |
|---|
| 538 |
|
|---|
| 539 |
Call ``str()`` or ``unicode()`` on the field to get its rendered HTML as a |
|---|
| 540 |
string or Unicode object, respectively:: |
|---|
| 541 |
|
|---|
| 542 |
>>> str(f['subject']) |
|---|
| 543 |
'<input id="id_subject" type="text" name="subject" maxlength="100" />' |
|---|
| 544 |
>>> unicode(f['subject']) |
|---|
| 545 |
u'<input id="id_subject" type="text" name="subject" maxlength="100" />' |
|---|
| 546 |
|
|---|
| 547 |
The field-specific output honors the form object's ``auto_id`` setting:: |
|---|
| 548 |
|
|---|
| 549 |
>>> f = ContactForm(auto_id=False) |
|---|
| 550 |
>>> print f['message'] |
|---|
| 551 |
<input type="text" name="message" /> |
|---|
| 552 |
>>> f = ContactForm(auto_id='id_%s') |
|---|
| 553 |
>>> print f['message'] |
|---|
| 554 |
<input type="text" name="message" id="id_message" /> |
|---|
| 555 |
|
|---|
| 556 |
For a field's list of errors, access the field's ``errors`` attribute. This |
|---|
| 557 |
is a list-like object that is displayed as an HTML ``<ul>`` when printed:: |
|---|
| 558 |
|
|---|
| 559 |
>>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''} |
|---|
| 560 |
>>> f = ContactForm(data, auto_id=False) |
|---|
| 561 |
>>> print f['message'] |
|---|
| 562 |
<input type="text" name="message" /> |
|---|
| 563 |
>>> f['message'].errors |
|---|
| 564 |
[u'This field is required.'] |
|---|
| 565 |
>>> print f['message'].errors |
|---|
| 566 |
<ul class="errorlist"><li>This field is required.</li></ul> |
|---|
| 567 |
>>> f['subject'].errors |
|---|
| 568 |
[] |
|---|
| 569 |
>>> print f['subject'].errors |
|---|
| 570 |
|
|---|
| 571 |
>>> str(f['subject'].errors) |
|---|
| 572 |
'' |
|---|
| 573 |
|
|---|
| 574 |
Fields |
|---|
| 575 |
====== |
|---|
| 576 |
|
|---|
| 577 |
When you create a ``Form`` class, the most important part is defining the |
|---|
| 578 |
fields of the form. Each field has custom validation logic, along with a few |
|---|
| 579 |
other hooks. |
|---|
| 580 |
|
|---|
| 581 |
Although the primary way you'll use ``Field`` classes is in ``Form`` classes, |
|---|
| 582 |
you can also instantiate them and use them directly to get a better idea of |
|---|
| 583 |
how they work. Each ``Field`` instance has a ``clean()`` method, which takes |
|---|
| 584 |
a single argument and either raises a ``django.newforms.ValidationError`` |
|---|
| 585 |
exception or returns the clean value:: |
|---|
| 586 |
|
|---|
| 587 |
>>> f = forms.EmailField() |
|---|
| 588 |
>>> f.clean('foo@example.com') |
|---|
| 589 |
u'foo@example.com' |
|---|
| 590 |
>>> f.clean(u'foo@example.com') |
|---|
| 591 |
u'foo@example.com' |
|---|
| 592 |
>>> f.clean('invalid e-mail address') |
|---|
| 593 |
Traceback (most recent call last): |
|---|
| 594 |
... |
|---|
| 595 |
ValidationError: [u'Enter a valid e-mail address.'] |
|---|
| 596 |
|
|---|
| 597 |
If you've used Django's old forms/validation framework, take care in noticing |
|---|
| 598 |
this ``ValidationError`` is different than the previous ``ValidationError``. |
|---|
| 599 |
This one lives at ``django.newforms.ValidationError`` rather than |
|---|
| 600 |
``django.core.validators.ValidationError``. |
|---|
| 601 |
|
|---|
| 602 |
Core field arguments |
|---|
| 603 |
-------------------- |
|---|
| 604 |
|
|---|
| 605 |
Each ``Field`` class constructor takes at least these arguments. Some |
|---|
| 606 |
``Field`` classes take additional, field-specific arguments, but the following |
|---|
| 607 |
should *always* be available: |
|---|
| 608 |
|
|---|
| 609 |
``required`` |
|---|
| 610 |
~~~~~~~~~~~~ |
|---|
| 611 |
|
|---|
| 612 |
By default, each ``Field`` class assumes the value is required, so if you pass |
|---|
| 613 |
an empty value -- either ``None`` or the empty string (``""``) -- then |
|---|
| 614 |
``clean()`` will raise a ``ValidationError`` exception:: |
|---|
| 615 |
|
|---|
| 616 |
>>> f = forms.CharField() |
|---|
| 617 |
>>> f.clean('foo') |
|---|
| 618 |
u'foo' |
|---|
| 619 |
>>> f.clean('') |
|---|
| 620 |
Traceback (most recent call last): |
|---|
| 621 |
... |
|---|
| 622 |
ValidationError: [u'This field is required.'] |
|---|
| 623 |
>>> f.clean(None) |
|---|
| 624 |
Traceback (most recent call last): |
|---|
| 625 |
... |
|---|
| 626 |
ValidationError: [u'This field is required.'] |
|---|
| 627 |
>>> f.clean(' ') |
|---|
| 628 |
u' ' |
|---|
| 629 |
>>> f.clean(0) |
|---|
| 630 |
u'0' |
|---|
| 631 |
>>> f.clean(True) |
|---|
| 632 |
u'True' |
|---|
| 633 |
>>> f.clean(False) |
|---|
| 634 |
u'False' |
|---|
| 635 |
|
|---|
| 636 |
To specify that a field is *not* required, pass ``required=False`` to the |
|---|
| 637 |
``Field`` constructor:: |
|---|
| 638 |
|
|---|
| 639 |
>>> f = forms.CharField(required=False) |
|---|
| 640 |
>>> f.clean('foo') |
|---|
| 641 |
u'foo' |
|---|
| 642 |
>>> f.clean('') |
|---|
| 643 |
u'' |
|---|
| 644 |
>>> f.clean(None) |
|---|
| 645 |
u'' |
|---|
| 646 |
>>> f.clean(0) |
|---|
| 647 |
u'0' |
|---|
| 648 |
>>> f.clean(True) |
|---|
| 649 |
u'True' |
|---|
| 650 |
>>> f.clean(False) |
|---|
| 651 |
u'False' |
|---|
| 652 |
|
|---|
| 653 |
If a ``Field`` has ``required=False`` and you pass ``clean()`` an empty value, |
|---|
| 654 |
then ``clean()`` will return a *normalized* empty value rather than raising |
|---|
| 655 |
``ValidationError``. For ``CharField``, this will be a Unicode empty string. |
|---|
| 656 |
For other ``Field`` classes, it might be ``None``. (This varies from field to |
|---|
| 657 |
field.) |
|---|
| 658 |
|
|---|
| 659 |
``label`` |
|---|
| 660 |
~~~~~~~~~ |
|---|
| 661 |
|
|---|
| 662 |
The ``label`` argument lets you specify the "human-friendly" label for this |
|---|
| 663 |
field. This is used when the ``Field`` is displayed in a ``Form``. |
|---|
| 664 |
|
|---|
| 665 |
As explained in _`Outputting forms as HTML` above, the default label for a |
|---|
| 666 |
``Field`` is generated from the field name by converting all underscores to |
|---|
| 667 |
spaces and upper-casing the first letter. Specify ``label`` if that default |
|---|
| 668 |
behavior doesn't result in an adequate label. |
|---|
| 669 |
|
|---|
| 670 |
Here's a full example ``Form`` that implements ``label`` for two of its fields. |
|---|
| 671 |
We've specified ``auto_id=False`` to simplify the output:: |
|---|
| 672 |
|
|---|
| 673 |
>>> class CommentForm(forms.Form): |
|---|
| 674 |
... name = forms.CharField(label='Your name') |
|---|
| 675 |
... url = forms.URLField(label='Your Web site', required=False) |
|---|
| 676 |
... comment = forms.CharField() |
|---|
| 677 |
>>> f = CommentForm(auto_id=False) |
|---|
| 678 |
>>> print f |
|---|
| 679 |
<tr><th>Your name:</th><td><input type="text" name="name" /></td></tr> |
|---|
| 680 |
<tr><th>Your Web site:</th><td><input type="text" name="url" /></td></tr> |
|---|
| 681 |
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr> |
|---|
| 682 |
|
|---|
| 683 |
``initial`` |
|---|
| 684 |
~~~~~~~~~~~ |
|---|
| 685 |
|
|---|
| 686 |
The ``initial`` argument lets you specify the initial value to use when |
|---|
| 687 |
rendering this ``Field`` in an unbound ``Form``. |
|---|
| 688 |
|
|---|
| 689 |
The use-case for this is when you want to display an "empty" form in which a |
|---|
| 690 |
field is initialized to a particular value. For example:: |
|---|
| 691 |
|
|---|
| 692 |
>>> class CommentForm(forms.Form): |
|---|
| 693 |
... name = forms.CharField(initial='Your name') |
|---|
| 694 |
... url = forms.URLField(initial='http://') |
|---|
| 695 |
... comment = forms.CharField() |
|---|
| 696 |
>>> f = CommentForm(auto_id=False) |
|---|
| 697 |
>>> print f |
|---|
| 698 |
<tr><th>Name:</th><td><input type="text" name="name" value="Your name" /></td></tr> |
|---|
| 699 |
<tr><th>Url:</th><td><input type="text" name="url" value="http://" /></td></tr> |
|---|
| 700 |
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr> |
|---|
| 701 |
|
|---|
| 702 |
You may be thinking, why not just pass a dictionary of the initial values as |
|---|
| 703 |
data when displaying the form? Well, if you do that, you'll trigger validation, |
|---|
| 704 |
and the HTML output will include any validation errors:: |
|---|
| 705 |
|
|---|
| 706 |
>>> class CommentForm(forms.Form): |
|---|
| 707 |
... name = forms.CharField() |
|---|
| 708 |
... url = forms.URLField() |
|---|
| 709 |
... comment = forms.CharField() |
|---|
| 710 |
>>> default_data = {'name': 'Your name', 'url': 'http://'} |
|---|
| 711 |
>>> f = CommentForm(default_data, auto_id=False) |
|---|
| 712 |
>>> print f |
|---|
| 713 |
<tr><th>Name:</th><td><input type="text" name="name" value="Your name" /></td></tr> |
|---|
| 714 |
<tr><th>Url:</th><td><ul class="errorlist"><li>Enter a valid URL.</li></ul><input type="text" name="url" value="http://" /></td></tr> |
|---|
| 715 |
<tr><th>Comment:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="comment" /></td></tr> |
|---|
| 716 |
|
|---|
| 717 |
This is why ``initial`` values are only displayed for unbound forms. For bound |
|---|
| 718 |
forms, the HTML output will use the bound data. |
|---|
| 719 |
|
|---|
| 720 |
Also note that ``initial`` values are *not* used as "fallback" data in |
|---|
| 721 |
validation if a particular field's value is not given. ``initial`` values are |
|---|
| 722 |
*only* intended for initial form display:: |
|---|
| 723 |
|
|---|
| 724 |
>>> class CommentForm(forms.Form): |
|---|
| 725 |
... name = forms.CharField(initial='Your name') |
|---|
| 726 |
... url = forms.URLField(initial='http://') |
|---|
| 727 |
... comment = forms.CharField() |
|---|
| 728 |
>>> data = {'name': '', 'url': '', 'comment': 'Foo'} |
|---|
| 729 |
>>> f = CommentForm(data) |
|---|
| 730 |
>>> f.is_valid() |
|---|
| 731 |
False |
|---|
| 732 |
# The form does *not* fall back to using the initial values. |
|---|
| 733 |
>>> f.errors |
|---|
| 734 |
{'url': [u'This field is required.'], 'name': [u'This field is required.']} |
|---|
| 735 |
|
|---|
| 736 |
``widget`` |
|---|
| 737 |
~~~~~~~~~~ |
|---|
| 738 |
|
|---|
| 739 |
The ``widget`` argument lets you specify a ``Widget`` class to use when |
|---|
| 740 |
rendering this ``Field``. See _`Widgets` below for more information. |
|---|
| 741 |
|
|---|
| 742 |
Dynamic initial values |
|---|
| 743 |
---------------------- |
|---|
| 744 |
|
|---|
| 745 |
The ``initial`` argument to ``Field`` (explained above) lets you hard-code the |
|---|
| 746 |
initial value for a ``Field`` -- but what if you want to declare the initial |
|---|
| 747 |
value at runtime? For example, you might want to fill in a ``username`` field |
|---|
| 748 |
with the username of the current session. |
|---|
| 749 |
|
|---|
| 750 |
To accomplish this, use the ``initial`` argument to a ``Form``. This argument, |
|---|
| 751 |
if given, should be a dictionary mapping field names to initial values. Only |
|---|
| 752 |
include the fields for which you're specifying an initial value; it's not |
|---|
| 753 |
necessary to include every field in your form. For example:: |
|---|
| 754 |
|
|---|
| 755 |
>>> class CommentForm(forms.Form): |
|---|
| 756 |
... name = forms.CharField() |
|---|
| 757 |
... url = forms.URLField() |
|---|
| 758 |
... comment = forms.CharField() |
|---|
| 759 |
>>> f = CommentForm(initial={'name': 'your username'}, auto_id=False) |
|---|
| 760 |
>>> print f |
|---|
| 761 |
<tr><th>Name:</th><td><input type="text" name="name" value="your username" /></td></tr> |
|---|
| 762 |
<tr><th>Url:</th><td><input type="text" name="url" /></td></tr> |
|---|
| 763 |
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr> |
|---|
| 764 |
>>> f = CommentForm(initial={'name': 'another username'}, auto_id=False) |
|---|
| 765 |
>>> print f |
|---|
| 766 |
<tr><th>Name:</th><td><input type="text" name="name" value="another username" /></td></tr> |
|---|
| 767 |
<tr><th>Url:</th><td><input type="text" name="url" /></td></tr> |
|---|
| 768 |
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr> |
|---|
| 769 |
|
|---|
| 770 |
Just like the ``initial`` parameter to ``Field``, these values are only |
|---|
| 771 |
displayed for unbound forms, and they're not used as fallback values if a |
|---|
| 772 |
particular value isn't provided. |
|---|
| 773 |
|
|---|
| 774 |
Finally, note that if a ``Field`` defines ``initial`` *and* you include |
|---|
| 775 |
``initial`` when instantiating the ``Form``, then the latter ``initial`` will |
|---|
| 776 |
have precedence. In this example, ``initial`` is provided both at the field |
|---|
| 777 |
level and at the form instance level, and the latter gets precedence:: |
|---|
| 778 |
|
|---|
| 779 |
>>> class CommentForm(forms.Form): |
|---|
| 780 |
... name = forms.CharField(initial='class') |
|---|
| 781 |
... url = forms.URLField() |
|---|
| 782 |
... comment = forms.CharField() |
|---|
| 783 |
>>> f = CommentForm(initial={'name': 'instance'}, auto_id=False) |
|---|
| 784 |
>>> print f |
|---|
| 785 |
<tr><th>Name:</th><td><input type="text" name="name" value="instance" /></td></tr> |
|---|
| 786 |
<tr><th>Url:</th><td><input type="text" name="url" /></td></tr> |
|---|
| 787 |
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr> |
|---|
| 788 |
|
|---|
| 789 |
More coming soon |
|---|
| 790 |
================ |
|---|
| 791 |
|
|---|
| 792 |
That's all the documentation for now. For more, see the file |
|---|
| 793 |
http://code.djangoproject.com/browser/django/trunk/tests/regressiontests/forms/tests.py |
|---|
| 794 |
-- the unit tests for ``django.newforms``. This can give you a good idea of |
|---|
| 795 |
what's possible. |
|---|
| 796 |
|
|---|
| 797 |
If you're really itching to learn and use this library, please be patient. |
|---|
| 798 |
We're working hard on finishing both the code and documentation. |
|---|
| 799 |
|
|---|
| 800 |
Widgets |
|---|
| 801 |
======= |
|---|