/docs/ref/forms/api.txt
Plain Text | 799 lines | 630 code | 169 blank | 0 comment | 0 complexity | c9016b67da6480ed1d1ba7f645398ded MD5 | raw file
Possible License(s): BSD-3-Clause
1============= 2The Forms API 3============= 4 5.. module:: django.forms.forms 6 7.. currentmodule:: django.forms 8 9.. admonition:: About this document 10 11 This document covers the gritty details of Django's forms API. You should 12 read the :doc:`introduction to working with forms </topics/forms/index>` 13 first. 14 15.. _ref-forms-api-bound-unbound: 16 17Bound and unbound forms 18----------------------- 19 20A :class:`Form` instance is either **bound** to a set of data, or **unbound**. 21 22 * If it's **bound** to a set of data, it's capable of validating that data 23 and rendering the form as HTML with the data displayed in the HTML. 24 25 * If it's **unbound**, it cannot do validation (because there's no data to 26 validate!), but it can still render the blank form as HTML. 27 28.. class:: Form 29 30To create an unbound :class:`Form` instance, simply instantiate the class:: 31 32 >>> f = ContactForm() 33 34To bind data to a form, pass the data as a dictionary as the first parameter to 35your :class:`Form` class constructor:: 36 37 >>> data = {'subject': 'hello', 38 ... 'message': 'Hi there', 39 ... 'sender': 'foo@example.com', 40 ... 'cc_myself': True} 41 >>> f = ContactForm(data) 42 43In this dictionary, the keys are the field names, which correspond to the 44attributes in your :class:`Form` class. The values are the data you're trying to 45validate. These will usually be strings, but there's no requirement that they be 46strings; the type of data you pass depends on the :class:`Field`, as we'll see 47in a moment. 48 49.. attribute:: Form.is_bound 50 51If you need to distinguish between bound and unbound form instances at runtime, 52check the value of the form's :attr:`~Form.is_bound` attribute:: 53 54 >>> f = ContactForm() 55 >>> f.is_bound 56 False 57 >>> f = ContactForm({'subject': 'hello'}) 58 >>> f.is_bound 59 True 60 61Note that passing an empty dictionary creates a *bound* form with empty data:: 62 63 >>> f = ContactForm({}) 64 >>> f.is_bound 65 True 66 67If you have a bound :class:`Form` instance and want to change the data somehow, 68or if you want to bind an unbound :class:`Form` instance to some data, create 69another :class:`Form` instance. There is no way to change data in a 70:class:`Form` instance. Once a :class:`Form` instance has been created, you 71should consider its data immutable, whether it has data or not. 72 73Using forms to validate data 74---------------------------- 75 76.. method:: Form.is_valid() 77 78The primary task of a :class:`Form` object is to validate data. With a bound 79:class:`Form` instance, call the :meth:`~Form.is_valid` method to run validation 80and return a boolean designating whether the data was valid:: 81 82 >>> data = {'subject': 'hello', 83 ... 'message': 'Hi there', 84 ... 'sender': 'foo@example.com', 85 ... 'cc_myself': True} 86 >>> f = ContactForm(data) 87 >>> f.is_valid() 88 True 89 90Let's try with some invalid data. In this case, ``subject`` is blank (an error, 91because all fields are required by default) and ``sender`` is not a valid 92e-mail address:: 93 94 >>> data = {'subject': '', 95 ... 'message': 'Hi there', 96 ... 'sender': 'invalid e-mail address', 97 ... 'cc_myself': True} 98 >>> f = ContactForm(data) 99 >>> f.is_valid() 100 False 101 102.. attribute:: Form.errors 103 104Access the :attr:`~Form.errors` attribute to get a dictionary of error 105messages:: 106 107 >>> f.errors 108 {'sender': [u'Enter a valid e-mail address.'], 'subject': [u'This field is required.']} 109 110In this dictionary, the keys are the field names, and the values are lists of 111Unicode strings representing the error messages. The error messages are stored 112in lists because a field can have multiple error messages. 113 114You can access :attr:`~Form.errors` without having to call 115:meth:`~Form.is_valid` first. The form's data will be validated the first time 116either you call :meth:`~Form.is_valid` or access :attr:`~Form.errors`. 117 118The validation routines will only get called once, regardless of how many times 119you access :attr:`~Form.errors` or call :meth:`~Form.is_valid`. This means that 120if validation has side effects, those side effects will only be triggered once. 121 122Behavior of unbound forms 123~~~~~~~~~~~~~~~~~~~~~~~~~ 124 125It's meaningless to validate a form with no data, but, for the record, here's 126what happens with unbound forms:: 127 128 >>> f = ContactForm() 129 >>> f.is_valid() 130 False 131 >>> f.errors 132 {} 133 134Dynamic initial values 135---------------------- 136 137.. attribute:: Form.initial 138 139Use :attr:`~Form.initial` to declare the initial value of form fields at 140runtime. For example, you might want to fill in a ``username`` field with the 141username of the current session. 142 143To accomplish this, use the :attr:`~Form.initial` argument to a :class:`Form`. 144This argument, if given, should be a dictionary mapping field names to initial 145values. Only include the fields for which you're specifying an initial value; 146it's not necessary to include every field in your form. For example:: 147 148 >>> f = ContactForm(initial={'subject': 'Hi there!'}) 149 150These values are only displayed for unbound forms, and they're not used as 151fallback values if a particular value isn't provided. 152 153Note that if a :class:`~django.forms.fields.Field` defines 154:attr:`~Form.initial` *and* you include ``initial`` when instantiating the 155``Form``, then the latter ``initial`` will have precedence. In this example, 156``initial`` is provided both at the field level and at the form instance level, 157and the latter gets precedence:: 158 159 >>> class CommentForm(forms.Form): 160 ... name = forms.CharField(initial='class') 161 ... url = forms.URLField() 162 ... comment = forms.CharField() 163 >>> f = CommentForm(initial={'name': 'instance'}, auto_id=False) 164 >>> print f 165 <tr><th>Name:</th><td><input type="text" name="name" value="instance" /></td></tr> 166 <tr><th>Url:</th><td><input type="text" name="url" /></td></tr> 167 <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr> 168 169Accessing "clean" data 170---------------------- 171 172.. attribute:: Form.cleaned_data 173 174Each field in a :class:`Form` class is responsible not only for validating 175data, but also for "cleaning" it -- normalizing it to a consistent format. This 176is a nice feature, because it allows data for a particular field to be input in 177a variety of ways, always resulting in consistent output. 178 179For example, :class:`~django.forms.DateField` normalizes input into a 180Python ``datetime.date`` object. Regardless of whether you pass it a string in 181the format ``'1994-07-15'``, a ``datetime.date`` object, or a number of other 182formats, ``DateField`` will always normalize it to a ``datetime.date`` object 183as long as it's valid. 184 185Once you've created a :class:`~Form` instance with a set of data and validated 186it, you can access the clean data via its ``cleaned_data`` attribute:: 187 188 >>> data = {'subject': 'hello', 189 ... 'message': 'Hi there', 190 ... 'sender': 'foo@example.com', 191 ... 'cc_myself': True} 192 >>> f = ContactForm(data) 193 >>> f.is_valid() 194 True 195 >>> f.cleaned_data 196 {'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'} 197 198Note that any text-based field -- such as ``CharField`` or ``EmailField`` -- 199always cleans the input into a Unicode string. We'll cover the encoding 200implications later in this document. 201 202If your data does *not* validate, your ``Form`` instance will not have a 203``cleaned_data`` attribute:: 204 205 >>> data = {'subject': '', 206 ... 'message': 'Hi there', 207 ... 'sender': 'invalid e-mail address', 208 ... 'cc_myself': True} 209 >>> f = ContactForm(data) 210 >>> f.is_valid() 211 False 212 >>> f.cleaned_data 213 Traceback (most recent call last): 214 ... 215 AttributeError: 'ContactForm' object has no attribute 'cleaned_data' 216 217``cleaned_data`` will always *only* contain a key for fields defined in the 218``Form``, even if you pass extra data when you define the ``Form``. In this 219example, we pass a bunch of extra fields to the ``ContactForm`` constructor, 220but ``cleaned_data`` contains only the form's fields:: 221 222 >>> data = {'subject': 'hello', 223 ... 'message': 'Hi there', 224 ... 'sender': 'foo@example.com', 225 ... 'cc_myself': True, 226 ... 'extra_field_1': 'foo', 227 ... 'extra_field_2': 'bar', 228 ... 'extra_field_3': 'baz'} 229 >>> f = ContactForm(data) 230 >>> f.is_valid() 231 True 232 >>> f.cleaned_data # Doesn't contain extra_field_1, etc. 233 {'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'} 234 235``cleaned_data`` will include a key and value for *all* fields defined in the 236``Form``, even if the data didn't include a value for fields that are not 237required. In this example, the data dictionary doesn't include a value for the 238``nick_name`` field, but ``cleaned_data`` includes it, with an empty value:: 239 240 >>> class OptionalPersonForm(Form): 241 ... first_name = CharField() 242 ... last_name = CharField() 243 ... nick_name = CharField(required=False) 244 >>> data = {'first_name': u'John', 'last_name': u'Lennon'} 245 >>> f = OptionalPersonForm(data) 246 >>> f.is_valid() 247 True 248 >>> f.cleaned_data 249 {'nick_name': u'', 'first_name': u'John', 'last_name': u'Lennon'} 250 251In this above example, the ``cleaned_data`` value for ``nick_name`` is set to an 252empty string, because ``nick_name`` is ``CharField``, and ``CharField``\s treat 253empty values as an empty string. Each field type knows what its "blank" value 254is -- e.g., for ``DateField``, it's ``None`` instead of the empty string. For 255full details on each field's behavior in this case, see the "Empty value" note 256for each field in the "Built-in ``Field`` classes" section below. 257 258You can write code to perform validation for particular form fields (based on 259their name) or for the form as a whole (considering combinations of various 260fields). More information about this is in :doc:`/ref/forms/validation`. 261 262Outputting forms as HTML 263------------------------ 264 265The second task of a ``Form`` object is to render itself as HTML. To do so, 266simply ``print`` it:: 267 268 >>> f = ContactForm() 269 >>> print f 270 <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr> 271 <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr> 272 <tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr> 273 <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr> 274 275If the form is bound to data, the HTML output will include that data 276appropriately. For example, if a field is represented by an 277``<input type="text">``, the data will be in the ``value`` attribute. If a 278field is represented by an ``<input type="checkbox">``, then that HTML will 279include ``checked="checked"`` if appropriate:: 280 281 >>> data = {'subject': 'hello', 282 ... 'message': 'Hi there', 283 ... 'sender': 'foo@example.com', 284 ... 'cc_myself': True} 285 >>> f = ContactForm(data) 286 >>> print f 287 <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" value="hello" /></td></tr> 288 <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" value="Hi there" /></td></tr> 289 <tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" value="foo@example.com" /></td></tr> 290 <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> 291 292This default output is a two-column HTML table, with a ``<tr>`` for each field. 293Notice the following: 294 295 * For flexibility, the output does *not* include the ``<table>`` and 296 ``</table>`` tags, nor does it include the ``<form>`` and ``</form>`` 297 tags or an ``<input type="submit">`` tag. It's your job to do that. 298 299 * Each field type has a default HTML representation. ``CharField`` and 300 ``EmailField`` are represented by an ``<input type="text">``. 301 ``BooleanField`` is represented by an ``<input type="checkbox">``. Note 302 these are merely sensible defaults; you can specify which HTML to use for 303 a given field by using widgets, which we'll explain shortly. 304 305 * The HTML ``name`` for each tag is taken directly from its attribute name 306 in the ``ContactForm`` class. 307 308 * The text label for each field -- e.g. ``'Subject:'``, ``'Message:'`` and 309 ``'Cc myself:'`` is generated from the field name by converting all 310 underscores to spaces and upper-casing the first letter. Again, note 311 these are merely sensible defaults; you can also specify labels manually. 312 313 * Each text label is surrounded in an HTML ``<label>`` tag, which points 314 to the appropriate form field via its ``id``. Its ``id``, in turn, is 315 generated by prepending ``'id_'`` to the field name. The ``id`` 316 attributes and ``<label>`` tags are included in the output by default, to 317 follow best practices, but you can change that behavior. 318 319Although ``<table>`` output is the default output style when you ``print`` a 320form, other output styles are available. Each style is available as a method on 321a form object, and each rendering method returns a Unicode object. 322 323``as_p()`` 324~~~~~~~~~~ 325 326.. method:: Form.as_p 327 328 ``as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>`` 329 containing one field:: 330 331 >>> f = ContactForm() 332 >>> f.as_p() 333 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>' 334 >>> print f.as_p() 335 <p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p> 336 <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p> 337 <p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p> 338 <p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p> 339 340``as_ul()`` 341~~~~~~~~~~~ 342 343.. method:: Form.as_ul 344 345 ``as_ul()`` renders the form as a series of ``<li>`` tags, with each 346 ``<li>`` containing one field. It does *not* include the ``<ul>`` or 347 ``</ul>``, so that you can specify any HTML attributes on the ``<ul>`` for 348 flexibility:: 349 350 >>> f = ContactForm() 351 >>> f.as_ul() 352 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>' 353 >>> print f.as_ul() 354 <li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li> 355 <li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li> 356 <li><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></li> 357 <li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li> 358 359``as_table()`` 360~~~~~~~~~~~~~~ 361 362.. method:: Form.as_table 363 364 Finally, ``as_table()`` outputs the form as an HTML ``<table>``. This is 365 exactly the same as ``print``. In fact, when you ``print`` a form object, 366 it calls its ``as_table()`` method behind the scenes:: 367 368 >>> f = ContactForm() 369 >>> f.as_table() 370 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>' 371 >>> print f.as_table() 372 <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr> 373 <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr> 374 <tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr> 375 <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr> 376 377Styling required or erroneous form rows 378~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 379 380.. versionadded:: 1.2 381 382It's pretty common to style form rows and fields that are required or have 383errors. For example, you might want to present required form rows in bold and 384highlight errors in red. 385 386The :class:`Form` class has a couple of hooks you can use to add ``class`` 387attributes to required rows or to rows with errors: simply set the 388:attr:`Form.error_css_class` and/or :attr:`Form.required_css_class` 389attributes:: 390 391 class ContactForm(Form): 392 error_css_class = 'error' 393 required_css_class = 'required' 394 395 # ... and the rest of your fields here 396 397Once you've done that, rows will be given ``"error"`` and/or ``"required"`` 398classes, as needed. The HTML will look something like:: 399 400 >>> f = ContactForm(data) 401 >>> print f.as_table() 402 <tr class="required"><th><label for="id_subject">Subject:</label> ... 403 <tr class="required"><th><label for="id_message">Message:</label> ... 404 <tr class="required error"><th><label for="id_sender">Sender:</label> ... 405 <tr><th><label for="id_cc_myself">Cc myself:<label> ... 406 407.. _ref-forms-api-configuring-label: 408 409Configuring HTML ``<label>`` tags 410~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 411 412An HTML ``<label>`` tag designates which label text is associated with which 413form element. This small enhancement makes forms more usable and more accessible 414to assistive devices. It's always a good idea to use ``<label>`` tags. 415 416By default, the form rendering methods include HTML ``id`` attributes on the 417form elements and corresponding ``<label>`` tags around the labels. The ``id`` 418attribute values are generated by prepending ``id_`` to the form field names. 419This behavior is configurable, though, if you want to change the ``id`` 420convention or remove HTML ``id`` attributes and ``<label>`` tags entirely. 421 422Use the ``auto_id`` argument to the ``Form`` constructor to control the label 423and ``id`` behavior. This argument must be ``True``, ``False`` or a string. 424 425If ``auto_id`` is ``False``, then the form output will not include ``<label>`` 426tags nor ``id`` attributes:: 427 428 >>> f = ContactForm(auto_id=False) 429 >>> print f.as_table() 430 <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /></td></tr> 431 <tr><th>Message:</th><td><input type="text" name="message" /></td></tr> 432 <tr><th>Sender:</th><td><input type="text" name="sender" /></td></tr> 433 <tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr> 434 >>> print f.as_ul() 435 <li>Subject: <input type="text" name="subject" maxlength="100" /></li> 436 <li>Message: <input type="text" name="message" /></li> 437 <li>Sender: <input type="text" name="sender" /></li> 438 <li>Cc myself: <input type="checkbox" name="cc_myself" /></li> 439 >>> print f.as_p() 440 <p>Subject: <input type="text" name="subject" maxlength="100" /></p> 441 <p>Message: <input type="text" name="message" /></p> 442 <p>Sender: <input type="text" name="sender" /></p> 443 <p>Cc myself: <input type="checkbox" name="cc_myself" /></p> 444 445If ``auto_id`` is set to ``True``, then the form output *will* include 446``<label>`` tags and will simply use the field name as its ``id`` for each form 447field:: 448 449 >>> f = ContactForm(auto_id=True) 450 >>> print f.as_table() 451 <tr><th><label for="subject">Subject:</label></th><td><input id="subject" type="text" name="subject" maxlength="100" /></td></tr> 452 <tr><th><label for="message">Message:</label></th><td><input type="text" name="message" id="message" /></td></tr> 453 <tr><th><label for="sender">Sender:</label></th><td><input type="text" name="sender" id="sender" /></td></tr> 454 <tr><th><label for="cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="cc_myself" /></td></tr> 455 >>> print f.as_ul() 456 <li><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></li> 457 <li><label for="message">Message:</label> <input type="text" name="message" id="message" /></li> 458 <li><label for="sender">Sender:</label> <input type="text" name="sender" id="sender" /></li> 459 <li><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></li> 460 >>> print f.as_p() 461 <p><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></p> 462 <p><label for="message">Message:</label> <input type="text" name="message" id="message" /></p> 463 <p><label for="sender">Sender:</label> <input type="text" name="sender" id="sender" /></p> 464 <p><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></p> 465 466If ``auto_id`` is set to a string containing the format character ``'%s'``, 467then the form output will include ``<label>`` tags, and will generate ``id`` 468attributes based on the format string. For example, for a format string 469``'field_%s'``, a field named ``subject`` will get the ``id`` value 470``'field_subject'``. Continuing our example:: 471 472 >>> f = ContactForm(auto_id='id_for_%s') 473 >>> print f.as_table() 474 <tr><th><label for="id_for_subject">Subject:</label></th><td><input id="id_for_subject" type="text" name="subject" maxlength="100" /></td></tr> 475 <tr><th><label for="id_for_message">Message:</label></th><td><input type="text" name="message" id="id_for_message" /></td></tr> 476 <tr><th><label for="id_for_sender">Sender:</label></th><td><input type="text" name="sender" id="id_for_sender" /></td></tr> 477 <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> 478 >>> print f.as_ul() 479 <li><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li> 480 <li><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></li> 481 <li><label for="id_for_sender">Sender:</label> <input type="text" name="sender" id="id_for_sender" /></li> 482 <li><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li> 483 >>> print f.as_p() 484 <p><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></p> 485 <p><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></p> 486 <p><label for="id_for_sender">Sender:</label> <input type="text" name="sender" id="id_for_sender" /></p> 487 <p><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></p> 488 489If ``auto_id`` is set to any other true value -- such as a string that doesn't 490include ``%s`` -- then the library will act as if ``auto_id`` is ``True``. 491 492By default, ``auto_id`` is set to the string ``'id_%s'``. 493 494Normally, a colon (``:``) will be appended after any label name when a form is 495rendered. It's possible to change the colon to another character, or omit it 496entirely, using the ``label_suffix`` parameter:: 497 498 >>> f = ContactForm(auto_id='id_for_%s', label_suffix='') 499 >>> print f.as_ul() 500 <li><label for="id_for_subject">Subject</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li> 501 <li><label for="id_for_message">Message</label> <input type="text" name="message" id="id_for_message" /></li> 502 <li><label for="id_for_sender">Sender</label> <input type="text" name="sender" id="id_for_sender" /></li> 503 <li><label for="id_for_cc_myself">Cc myself</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li> 504 >>> f = ContactForm(auto_id='id_for_%s', label_suffix=' ->') 505 >>> print f.as_ul() 506 <li><label for="id_for_subject">Subject -></label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li> 507 <li><label for="id_for_message">Message -></label> <input type="text" name="message" id="id_for_message" /></li> 508 <li><label for="id_for_sender">Sender -></label> <input type="text" name="sender" id="id_for_sender" /></li> 509 <li><label for="id_for_cc_myself">Cc myself -></label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li> 510 511Note that the label suffix is added only if the last character of the 512label isn't a punctuation character (``.``, ``!``, ``?`` or ``:``) 513 514Notes on field ordering 515~~~~~~~~~~~~~~~~~~~~~~~ 516 517In the ``as_p()``, ``as_ul()`` and ``as_table()`` shortcuts, the fields are 518displayed in the order in which you define them in your form class. For 519example, in the ``ContactForm`` example, the fields are defined in the order 520``subject``, ``message``, ``sender``, ``cc_myself``. To reorder the HTML 521output, just change the order in which those fields are listed in the class. 522 523How errors are displayed 524~~~~~~~~~~~~~~~~~~~~~~~~ 525 526If you render a bound ``Form`` object, the act of rendering will automatically 527run the form's validation if it hasn't already happened, and the HTML output 528will include the validation errors as a ``<ul class="errorlist">`` near the 529field. The particular positioning of the error messages depends on the output 530method you're using:: 531 532 >>> data = {'subject': '', 533 ... 'message': 'Hi there', 534 ... 'sender': 'invalid e-mail address', 535 ... 'cc_myself': True} 536 >>> f = ContactForm(data, auto_id=False) 537 >>> print f.as_table() 538 <tr><th>Subject:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" /></td></tr> 539 <tr><th>Message:</th><td><input type="text" name="message" value="Hi there" /></td></tr> 540 <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> 541 <tr><th>Cc myself:</th><td><input checked="checked" type="checkbox" name="cc_myself" /></td></tr> 542 >>> print f.as_ul() 543 <li><ul class="errorlist"><li>This field is required.</li></ul>Subject: <input type="text" name="subject" maxlength="100" /></li> 544 <li>Message: <input type="text" name="message" value="Hi there" /></li> 545 <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> 546 <li>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></li> 547 >>> print f.as_p() 548 <p><ul class="errorlist"><li>This field is required.</li></ul></p> 549 <p>Subject: <input type="text" name="subject" maxlength="100" /></p> 550 <p>Message: <input type="text" name="message" value="Hi there" /></p> 551 <p><ul class="errorlist"><li>Enter a valid e-mail address.</li></ul></p> 552 <p>Sender: <input type="text" name="sender" value="invalid e-mail address" /></p> 553 <p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p> 554 555Customizing the error list format 556~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 557 558By default, forms use ``django.forms.util.ErrorList`` to format validation 559errors. If you'd like to use an alternate class for displaying errors, you can 560pass that in at construction time:: 561 562 >>> from django.forms.util import ErrorList 563 >>> class DivErrorList(ErrorList): 564 ... def __unicode__(self): 565 ... return self.as_divs() 566 ... def as_divs(self): 567 ... if not self: return u'' 568 ... return u'<div class="errorlist">%s</div>' % ''.join([u'<div class="error">%s</div>' % e for e in self]) 569 >>> f = ContactForm(data, auto_id=False, error_class=DivErrorList) 570 >>> f.as_p() 571 <div class="errorlist"><div class="error">This field is required.</div></div> 572 <p>Subject: <input type="text" name="subject" maxlength="100" /></p> 573 <p>Message: <input type="text" name="message" value="Hi there" /></p> 574 <div class="errorlist"><div class="error">Enter a valid e-mail address.</div></div> 575 <p>Sender: <input type="text" name="sender" value="invalid e-mail address" /></p> 576 <p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p> 577 578More granular output 579~~~~~~~~~~~~~~~~~~~~ 580 581The ``as_p()``, ``as_ul()`` and ``as_table()`` methods are simply shortcuts for 582lazy developers -- they're not the only way a form object can be displayed. 583 584.. class:: BoundField 585 586 Used to display HTML or access attributes for a single field of a 587 :class:`Form` instance. 588 589 The :meth:`__unicode__` and :meth:`__str__` methods of this object displays 590 the HTML for this field. 591 592To retrieve a single ``BoundField``, use dictionary lookup syntax on your form 593using the field's name as the key:: 594 595 >>> form = ContactForm() 596 >>> print form['subject'] 597 <input id="id_subject" type="text" name="subject" maxlength="100" /> 598 599To retrieve all ``BoundField`` objects, iterate the form:: 600 601 >>> form = ContactForm() 602 >>> for boundfield in form: print boundfield 603 <input id="id_subject" type="text" name="subject" maxlength="100" /> 604 <input type="text" name="message" id="id_message" /> 605 <input type="text" name="sender" id="id_sender" /> 606 <input type="checkbox" name="cc_myself" id="id_cc_myself" /> 607 608The field-specific output honors the form object's ``auto_id`` setting:: 609 610 >>> f = ContactForm(auto_id=False) 611 >>> print f['message'] 612 <input type="text" name="message" /> 613 >>> f = ContactForm(auto_id='id_%s') 614 >>> print f['message'] 615 <input type="text" name="message" id="id_message" /> 616 617For a field's list of errors, access the field's ``errors`` attribute. 618 619.. attribute:: BoundField.errors 620 621 A list-like object that is displayed as an HTML ``<ul class="errorlist">`` 622 when printed:: 623 624 >>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''} 625 >>> f = ContactForm(data, auto_id=False) 626 >>> print f['message'] 627 <input type="text" name="message" /> 628 >>> f['message'].errors 629 [u'This field is required.'] 630 >>> print f['message'].errors 631 <ul class="errorlist"><li>This field is required.</li></ul> 632 >>> f['subject'].errors 633 [] 634 >>> print f['subject'].errors 635 636 >>> str(f['subject'].errors) 637 '' 638 639.. method:: BoundField.css_classes() 640 641 .. versionadded:: 1.2 642 643When you use Django's rendering shortcuts, CSS classes are used to 644indicate required form fields or fields that contain errors. If you're 645manually rendering a form, you can access these CSS classes using the 646``css_classes`` method:: 647 648 >>> f = ContactForm(data) 649 >>> f['message'].css_classes() 650 'required' 651 652If you want to provide some additional classes in addition to the 653error and required classes that may be required, you can provide 654those classes as an argument:: 655 656 >>> f = ContactForm(data) 657 >>> f['message'].css_classes('foo bar') 658 'foo bar required' 659 660.. method:: BoundField.value() 661 662 .. versionadded:: 1.3 663 664Use this method to render the raw value of this field as it would be rendered 665by a ``Widget``:: 666 667 >>> initial = {'subject': 'welcome'} 668 >>> unbound_form = ContactForm(initial=initial) 669 >>> bound_form = ContactForm(data, initial=initial) 670 >>> print unbound_form['subject'].value() 671 welcome 672 >>> print bound_form['subject'].value() 673 hi 674 675.. _binding-uploaded-files: 676 677Binding uploaded files to a form 678-------------------------------- 679 680Dealing with forms that have ``FileField`` and ``ImageField`` fields 681is a little more complicated than a normal form. 682 683Firstly, in order to upload files, you'll need to make sure that your 684``<form>`` element correctly defines the ``enctype`` as 685``"multipart/form-data"``:: 686 687 <form enctype="multipart/form-data" method="post" action="/foo/"> 688 689Secondly, when you use the form, you need to bind the file data. File 690data is handled separately to normal form data, so when your form 691contains a ``FileField`` and ``ImageField``, you will need to specify 692a second argument when you bind your form. So if we extend our 693ContactForm to include an ``ImageField`` called ``mugshot``, we 694need to bind the file data containing the mugshot image:: 695 696 # Bound form with an image field 697 >>> from django.core.files.uploadedfile import SimpleUploadedFile 698 >>> data = {'subject': 'hello', 699 ... 'message': 'Hi there', 700 ... 'sender': 'foo@example.com', 701 ... 'cc_myself': True} 702 >>> file_data = {'mugshot': SimpleUploadedFile('face.jpg', <file data>)} 703 >>> f = ContactFormWithMugshot(data, file_data) 704 705In practice, you will usually specify ``request.FILES`` as the source 706of file data (just like you use ``request.POST`` as the source of 707form data):: 708 709 # Bound form with an image field, data from the request 710 >>> f = ContactFormWithMugshot(request.POST, request.FILES) 711 712Constructing an unbound form is the same as always -- just omit both 713form data *and* file data:: 714 715 # Unbound form with a image field 716 >>> f = ContactFormWithMugshot() 717 718Testing for multipart forms 719~~~~~~~~~~~~~~~~~~~~~~~~~~~ 720 721If you're writing reusable views or templates, you may not know ahead of time 722whether your form is a multipart form or not. The ``is_multipart()`` method 723tells you whether the form requires multipart encoding for submission:: 724 725 >>> f = ContactFormWithMugshot() 726 >>> f.is_multipart() 727 True 728 729Here's an example of how you might use this in a template:: 730 731 {% if form.is_multipart %} 732 <form enctype="multipart/form-data" method="post" action="/foo/"> 733 {% else %} 734 <form method="post" action="/foo/"> 735 {% endif %} 736 {{ form }} 737 </form> 738 739Subclassing forms 740----------------- 741 742If you have multiple ``Form`` classes that share fields, you can use 743subclassing to remove redundancy. 744 745When you subclass a custom ``Form`` class, the resulting subclass will 746include all fields of the parent class(es), followed by the fields you define 747in the subclass. 748 749In this example, ``ContactFormWithPriority`` contains all the fields from 750``ContactForm``, plus an additional field, ``priority``. The ``ContactForm`` 751fields are ordered first:: 752 753 >>> class ContactFormWithPriority(ContactForm): 754 ... priority = forms.CharField() 755 >>> f = ContactFormWithPriority(auto_id=False) 756 >>> print f.as_ul() 757 <li>Subject: <input type="text" name="subject" maxlength="100" /></li> 758 <li>Message: <input type="text" name="message" /></li> 759 <li>Sender: <input type="text" name="sender" /></li> 760 <li>Cc myself: <input type="checkbox" name="cc_myself" /></li> 761 <li>Priority: <input type="text" name="priority" /></li> 762 763It's possible to subclass multiple forms, treating forms as "mix-ins." In this 764example, ``BeatleForm`` subclasses both ``PersonForm`` and ``InstrumentForm`` 765(in that order), and its field list includes the fields from the parent 766classes:: 767 768 >>> class PersonForm(Form): 769 ... first_name = CharField() 770 ... last_name = CharField() 771 >>> class InstrumentForm(Form): 772 ... instrument = CharField() 773 >>> class BeatleForm(PersonForm, InstrumentForm): 774 ... haircut_type = CharField() 775 >>> b = BeatleForm(auto_id=False) 776 >>> print b.as_ul() 777 <li>First name: <input type="text" name="first_name" /></li> 778 <li>Last name: <input type="text" name="last_name" /></li> 779 <li>Instrument: <input type="text" name="instrument" /></li> 780 <li>Haircut type: <input type="text" name="haircut_type" /></li> 781 782.. _form-prefix: 783 784Prefixes for forms 785------------------ 786 787.. attribute:: Form.prefix 788 789You can put several Django forms inside one ``<form>`` tag. To give each 790``Form`` its own namespace, use the ``prefix`` keyword argument:: 791 792 >>> mother = PersonForm(prefix="mother") 793 >>> father = PersonForm(prefix="father") 794 >>> print mother.as_ul() 795 <li><label for="id_mother-first_name">First name:</label> <input type="text" name="mother-first_name" id="id_mother-first_name" /></li> 796 <li><label for="id_mother-last_name">Last name:</label> <input type="text" name="mother-last_name" id="id_mother-last_name" /></li> 797 >>> print father.as_ul() 798 <li><label for="id_father-first_name">First name:</label> <input type="text" name="father-first_name" id="id_father-first_name" /></li> 799 <li><label for="id_father-last_name">Last name:</label> <input type="text" name="father-last_name" id="id_father-last_name" /></li>