|
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 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: |
|
16 |
|
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:: |
|
21 |
|
22 from django import forms # old |
|
23 from django import oldforms as forms # new |
|
24 |
|
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 |
|
29 previous bullet. |
|
30 |
|
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``. |
|
34 |
|
35 With this in mind, we recommend you use the following import statement when |
|
36 using ``django.newforms``:: |
|
37 |
|
38 from django import newforms as forms |
|
39 |
|
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. |
|
43 |
|
44 If you prefer "``import *``" syntax, you can do the following:: |
|
45 |
|
46 from django.newforms import * |
|
47 |
|
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. |
|
51 |
|
52 Overview |
|
53 ======== |
|
54 |
|
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. |
|
59 |
|
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. |
|
64 |
|
65 The library deals with these concepts: |
|
66 |
|
67 * **Widget** -- A class that corresponds to an HTML form widget, e.g. |
|
68 ``<input type="text">`` or ``<textarea>``. This handles rendering of the |
|
69 widget as HTML. |
|
70 |
|
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. |
|
73 |
|
74 * **Form** -- A collection of fields that knows how to validate itself and |
|
75 display itself as HTML. |
|
76 |
|
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 |
|
81 library). |
|
82 |
|
83 Form objects |
|
84 ============ |
|
85 |
|
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 |
|
91 personal Web site. |
|
92 |
|
93 Start with this basic ``Form`` subclass, which we'll call ``ContactForm``:: |
|
94 |
|
95 from django import newforms as forms |
|
96 |
|
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() |
|
102 |
|
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`` -- |
|
106 shortly. |
|
107 |
|
108 Creating ``Form`` instances |
|
109 --------------------------- |
|
110 |
|
111 A ``Form`` instance is either **bound** or **unbound** to a set of data. |
|
112 |
|
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. |
|
115 |
|
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. |
|
118 |
|
119 To create an unbound ``Form`` instance, simply instantiate the class:: |
|
120 |
|
121 >>> f = ContactForm() |
|
122 |
|
123 To bind data to a form, pass the data as a dictionary as the first parameter to |
|
124 your ``Form`` class constructor:: |
|
125 |
|
126 >>> data = {'subject': 'hello', |
|
127 ... 'message': 'Hi there', |
|
128 ... 'sender': 'foo@example.com', |
|
129 ... 'cc_myself': True} |
|
130 >>> f = ContactForm(data) |
|
131 |
|
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 |
|
136 see in a moment. |
|
137 |
|
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:: |
|
140 |
|
141 >>> f = ContactForm() |
|
142 >>> f.is_bound |
|
143 False |
|
144 >>> f = ContactForm({'subject': 'hello'}) |
|
145 >>> f.is_bound |
|
146 True |
|
147 |
|
148 Note that passing an empty dictionary creates a *bound* form with empty data:: |
|
149 |
|
150 >>> f = ContactForm({}) |
|
151 >>> f.is_bound |
|
152 True |
|
153 |
|
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. |
|
159 |
|
160 Using forms to validate data |
|
161 ---------------------------- |
|
162 |
|
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:: |
|
166 |
|
167 >>> data = {'subject': 'hello', |
|
168 ... 'message': 'Hi there', |
|
169 ... 'sender': 'foo@example.com', |
|
170 ... 'cc_myself': True} |
|
171 >>> f = ContactForm(data) |
|
172 >>> f.is_valid() |
|
173 True |
|
174 |
|
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 |
|
177 e-mail address:: |
|
178 |
|
179 >>> data = {'subject': '', |
|
180 ... 'message': 'Hi there', |
|
181 ... 'sender': 'invalid e-mail address', |
|
182 ... 'cc_myself': True} |
|
183 >>> f = ContactForm(data) |
|
184 >>> f.is_valid() |
|
185 False |
|
186 |
|
187 Access the ``Form`` attribute ``errors`` to get a dictionary of error messages:: |
|
188 |
|
189 >>> f.errors |
|
190 {'sender': [u'Enter a valid e-mail address.'], 'subject': [u'This field is required.']} |
|
191 |
|
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. |
|
195 |
|
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 |
|
198 access ``errors``. |
|
199 |
|
200 Behavior of unbound forms |
|
201 ~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
202 |
|
203 It's meaningless to validate a form with no data, but, for the record, here's |
|
204 what happens with unbound forms:: |
|
205 |
|
206 >>> f = ContactForm() |
|
207 >>> f.is_valid() |
|
208 False |
|
209 >>> f.errors |
|
210 {} |
|
211 |
|
212 Accessing "clean" data |
|
213 ---------------------- |
|
214 |
|
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. |
|
219 |
|
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 |
|
224 it's valid. |
|
225 |
|
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`` |
|
228 object:: |
|
229 |
|
230 >>> data = {'subject': 'hello', |
|
231 ... 'message': 'Hi there', |
|
232 ... 'sender': 'foo@example.com', |
|
233 ... 'cc_myself': True} |
|
234 >>> f = ContactForm(data) |
|
235 >>> f.is_valid() |
|
236 True |
|
237 >>> f.clean_data |
|
238 {'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'} |
|
239 |
|
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. |
|
243 |
|
244 If your data does *not* validate, your ``Form`` instance will not have a |
|
245 ``clean_data`` attribute:: |
|
246 |
|
247 >>> data = {'subject': '', |
|
248 ... 'message': 'Hi there', |
|
249 ... 'sender': 'invalid e-mail address', |
|
250 ... 'cc_myself': True} |
|
251 >>> f = ContactForm(data) |
|
252 >>> f.is_valid() |
|
253 False |
|
254 >>> f.clean_data |
|
255 Traceback (most recent call last): |
|
256 ... |
|
257 AttributeError: 'ContactForm' object has no attribute 'clean_data' |
|
258 |
|
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:: |
|
263 |
|
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) |
|
272 >>> f.is_valid() |
|
273 True |
|
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'} |
|
276 |
|
277 Behavior of unbound forms |
|
278 ~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
279 |
|
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:: |
|
282 |
|
283 >>> f = ContactForm() |
|
284 >>> f.clean_data |
|
285 Traceback (most recent call last): |
|
286 ... |
|
287 AttributeError: 'ContactForm' object has no attribute 'clean_data' |
|
288 |
|
289 Outputting forms as HTML |
|
290 ------------------------ |
|
291 |
|
292 The second task of a ``Form`` object is to render itself as HTML. To do so, |
|
293 simply ``print`` it:: |
|
294 |
|
295 >>> f = ContactForm() |
|
296 >>> print f |
|
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> |
|
301 |
|
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:: |
|
307 |
|
308 >>> data = {'subject': 'hello', |
|
309 ... 'message': 'Hi there', |
|
310 ... 'sender': 'foo@example.com', |
|
311 ... 'cc_myself': True} |
|
312 >>> f = ContactForm(data) |
|
313 >>> print f |
|
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> |
|
318 |
|
319 This default output is a two-column HTML table, with a ``<tr>`` for each field. |
|
320 Notice the following: |
|
321 |
|
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. |
|
325 |
|
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. |
|
331 |
|
332 * The HTML ``name`` for each tag is taken directly from its attribute name |
|
333 in the ``ContactForm`` class. |
|
334 |
|
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. |
|
339 |
|
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. |
|
345 |
|
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. |
|
349 |
|
350 ``as_p()`` |
|
351 ~~~~~~~~~~ |
|
352 |
|
353 ``Form.as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>`` |
|
354 containing one field:: |
|
355 |
|
356 >>> f = ContactForm() |
|
357 >>> f.as_p() |
|
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>' |
|
359 >>> print f.as_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> |
|
364 |
|
365 ``as_ul()`` |
|
366 ~~~~~~~~~~~ |
|
367 |
|
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:: |
|
371 |
|
372 >>> f = ContactForm() |
|
373 >>> f.as_ul() |
|
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>' |
|
375 >>> print f.as_ul() |
|
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> |
|
380 |
|
381 ``as_table()`` |
|
382 ~~~~~~~~~~~~~~ |
|
383 |
|
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:: |
|
387 |
|
388 >>> f = ContactForm() |
|
389 >>> f.as_table() |
|
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> |
|
396 |
|
397 Configuring HTML ``<label>`` tags |
|
398 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
399 |
|
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. |
|
403 |
|
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. |
|
409 |
|
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. |
|
412 |
|
413 If ``auto_id`` is ``False``, then the form output will not include ``<label>`` |
|
414 tags nor ``id`` attributes:: |
|
415 |
|
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> |
|
422 >>> print f.as_ul() |
|
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> |
|
427 >>> print f.as_p() |
|
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> |
|
432 |
|
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 |
|
435 field:: |
|
436 |
|
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> |
|
443 >>> print f.as_ul() |
|
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> |
|
448 >>> print f.as_p() |
|
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> |
|
453 |
|
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:: |
|
459 |
|
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> |
|
466 >>> print f.as_ul() |
|
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> |
|
471 >>> print f.as_p() |
|
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> |
|
476 |
|
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``. |
|
479 |
|
480 By default, ``auto_id`` is set to the string ``'id_%s'``. |
|
481 |
|
482 Notes on field ordering |
|
483 ~~~~~~~~~~~~~~~~~~~~~~~ |
|
484 |
|
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. |
|
490 |
|
491 How errors are displayed |
|
492 ~~~~~~~~~~~~~~~~~~~~~~~~ |
|
493 |
|
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:: |
|
498 |
|
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> |
|
509 >>> print f.as_ul() |
|
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> |
|
514 >>> print f.as_p() |
|
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> |
|
521 |
|
522 More granular output |
|
523 ~~~~~~~~~~~~~~~~~~~~ |
|
524 |
|
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. |
|
527 |
|
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:: |
|
530 |
|
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" /> |
|
540 |
|
541 Call ``str()`` or ``unicode()`` on the field to get its rendered HTML as a |
|
542 string or Unicode object, respectively:: |
|
543 |
|
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" />' |
|
548 |
|
549 The field-specific output honors the form object's ``auto_id`` setting:: |
|
550 |
|
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" /> |
|
557 |
|
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:: |
|
560 |
|
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 |
|
570 [] |
|
571 >>> print f['subject'].errors |
|
572 |
|
573 >>> str(f['subject'].errors) |
|
574 '' |
|
575 |
|
576 Subclassing forms |
|
577 ----------------- |
|
578 |
|
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 |
|
581 in the subclass. |
|
582 |
|
583 In this example, ``ContactFormWithPriority`` contains all the fields from |
|
584 ``ContactForm``, plus an additional field, ``priority``. The ``ContactForm`` |
|
585 fields are ordered first:: |
|
586 |
|
587 >>> class ContactFormWithPriority(ContactForm): |
|
588 ... priority = forms.CharField() |
|
589 >>> f = ContactFormWithPriority(auto_id=False) |
|
590 >>> print f.as_ul() |
|
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> |
|
596 |
|
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 |
|
600 classes:: |
|
601 |
|
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) |
|
610 >>> print b.as_ul() |
|
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> |
|
615 |
|
616 Fields |
|
617 ====== |
|
618 |
|
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 |
|
621 other hooks. |
|
622 |
|
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:: |
|
628 |
|
629 >>> f = forms.EmailField() |
|
630 >>> f.clean('foo@example.com') |
|
631 u'foo@example.com' |
|
632 >>> f.clean(u'foo@example.com') |
|
633 u'foo@example.com' |
|
634 >>> f.clean('invalid e-mail address') |
|
635 Traceback (most recent call last): |
|
636 ... |
|
637 ValidationError: [u'Enter a valid e-mail address.'] |
|
638 |
|
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``. |
|
643 |
|
644 Core field arguments |
|
645 -------------------- |
|
646 |
|
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: |
|
650 |
|
651 ``required`` |
|
652 ~~~~~~~~~~~~ |
|
653 |
|
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:: |
|
657 |
|
658 >>> f = forms.CharField() |
|
659 >>> f.clean('foo') |
|
660 u'foo' |
|
661 >>> f.clean('') |
|
662 Traceback (most recent call last): |
|
663 ... |
|
664 ValidationError: [u'This field is required.'] |
|
665 >>> f.clean(None) |
|
666 Traceback (most recent call last): |
|
667 ... |
|
668 ValidationError: [u'This field is required.'] |
|
669 >>> f.clean(' ') |
|
670 u' ' |
|
671 >>> f.clean(0) |
|
672 u'0' |
|
673 >>> f.clean(True) |
|
674 u'True' |
|
675 >>> f.clean(False) |
|
676 u'False' |
|
677 |
|
678 To specify that a field is *not* required, pass ``required=False`` to the |
|
679 ``Field`` constructor:: |
|
680 |
|
681 >>> f = forms.CharField(required=False) |
|
682 >>> f.clean('foo') |
|
683 u'foo' |
|
684 >>> f.clean('') |
|
685 u'' |
|
686 >>> f.clean(None) |
|
687 u'' |
|
688 >>> f.clean(0) |
|
689 u'0' |
|
690 >>> f.clean(True) |
|
691 u'True' |
|
692 >>> f.clean(False) |
|
693 u'False' |
|
694 |
|
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 |
|
699 field.) |
|
700 |
|
701 ``label`` |
|
702 ~~~~~~~~~ |
|
703 |
|
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``. |
|
706 |
|
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. |
|
711 |
|
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:: |
|
714 |
|
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) |
|
720 >>> print f |
|
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> |
|
724 |
|
725 ``initial`` |
|
726 ~~~~~~~~~~~ |
|
727 |
|
728 The ``initial`` argument lets you specify the initial value to use when |
|
729 rendering this ``Field`` in an unbound ``Form``. |
|
730 |
|
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:: |
|
733 |
|
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) |
|
739 >>> print f |
|
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> |
|
743 |
|
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:: |
|
747 |
|
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) |
|
754 >>> print f |
|
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> |
|
758 |
|
759 This is why ``initial`` values are only displayed for unbound forms. For bound |
|
760 forms, the HTML output will use the bound data. |
|
761 |
|
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:: |
|
765 |
|
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) |
|
772 >>> f.is_valid() |
|
773 False |
|
774 # The form does *not* fall back to using the initial values. |
|
775 >>> f.errors |
|
776 {'url': [u'This field is required.'], 'name': [u'This field is required.']} |
|
777 |
|
778 ``widget`` |
|
779 ~~~~~~~~~~ |
|
780 |
|
781 The ``widget`` argument lets you specify a ``Widget`` class to use when |
|
782 rendering this ``Field``. See _`Widgets` below for more information. |
|
783 |
|
784 ``help_text`` |
|
785 ~~~~~~~~~~~~~ |
|
786 |
|
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``. |
|
790 |
|
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:: |
|
793 |
|
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> |
|
805 >>> print f.as_ul() |
|
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> |
|
810 >>> print f.as_p() |
|
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> |
|
815 |
|
816 Dynamic initial values |
|
817 ---------------------- |
|
818 |
|
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. |
|
823 |
|
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:: |
|
828 |
|
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) |
|
834 >>> print f |
|
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) |
|
839 >>> print f |
|
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> |
|
843 |
|
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. |
|
847 |
|
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:: |
|
852 |
|
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) |
|
858 >>> print f |
|
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> |
|
862 |
|
863 More coming soon |
|
864 ================ |
|
865 |
|
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 |
|
869 what's possible. |
|
870 |
|
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. |
|
873 |
|
874 Widgets |
|
875 ======= |