| 1 |
============= |
| 2 |
The Forms API |
| 3 |
============= |
| 4 |
|
| 5 |
.. module:: django.forms |
| 6 |
|
| 7 |
.. admonition:: About this document |
| 8 |
|
| 9 |
This document covers the gritty details of Django's forms API. You should |
| 10 |
read the :doc:`introduction to working with forms </topics/forms/index>` |
| 11 |
first. |
| 12 |
|
| 13 |
.. _ref-forms-api-bound-unbound: |
| 14 |
|
| 15 |
Bound and unbound forms |
| 16 |
======================= |
| 17 |
|
| 18 |
A :class:`Form` instance is either **bound** to a set of data, or **unbound**. |
| 19 |
|
| 20 |
* If it's **bound** to a set of data, it's capable of validating that data |
| 21 |
and rendering the form as HTML with the data displayed in the HTML. |
| 22 |
|
| 23 |
* If it's **unbound**, it cannot do validation (because there's no data to |
| 24 |
validate!), but it can still render the blank form as HTML. |
| 25 |
|
| 26 |
.. class:: Form |
| 27 |
|
| 28 |
To create an unbound :class:`Form` instance, instantiate the class: |
| 29 |
|
| 30 |
.. code-block:: pycon |
| 31 |
|
| 32 |
>>> f = ContactForm() |
| 33 |
|
| 34 |
To bind data to a form, pass the data as a dictionary as the first parameter to |
| 35 |
your :class:`Form` class constructor: |
| 36 |
|
| 37 |
.. code-block:: pycon |
| 38 |
|
| 39 |
>>> data = { |
| 40 |
... "subject": "hello", |
| 41 |
... "message": "Hi there", |
| 42 |
... "sender": "[email protected]", |
| 43 |
... "cc_myself": True, |
| 44 |
... } |
| 45 |
>>> f = ContactForm(data) |
| 46 |
|
| 47 |
In this dictionary, the keys are the field names, which correspond to the |
| 48 |
attributes in your :class:`Form` class. The values are the data you're trying to |
| 49 |
validate. These will usually be strings, but there's no requirement that they be |
| 50 |
strings; the type of data you pass depends on the :class:`Field`, as we'll see |
| 51 |
in a moment. |
| 52 |
|
| 53 |
.. attribute:: Form.is_bound |
| 54 |
|
| 55 |
If you need to distinguish between bound and unbound form instances at runtime, |
| 56 |
check the value of the form's :attr:`~Form.is_bound` attribute: |
| 57 |
|
| 58 |
.. code-block:: pycon |
| 59 |
|
| 60 |
>>> f = ContactForm() |
| 61 |
>>> f.is_bound |
| 62 |
False |
| 63 |
>>> f = ContactForm({"subject": "hello"}) |
| 64 |
>>> f.is_bound |
| 65 |
True |
| 66 |
|
| 67 |
Note that passing an empty dictionary creates a *bound* form with empty data: |
| 68 |
|
| 69 |
.. code-block:: pycon |
| 70 |
|
| 71 |
>>> f = ContactForm({}) |
| 72 |
>>> f.is_bound |
| 73 |
True |
| 74 |
|
| 75 |
If you have a bound :class:`Form` instance and want to change the data somehow, |
| 76 |
or if you want to bind an unbound :class:`Form` instance to some data, create |
| 77 |
another :class:`Form` instance. There is no way to change data in a |
| 78 |
:class:`Form` instance. Once a :class:`Form` instance has been created, you |
| 79 |
should consider its data immutable, whether it has data or not. |
| 80 |
|
| 81 |
Using forms to validate data |
| 82 |
============================ |
| 83 |
|
| 84 |
.. method:: Form.clean() |
| 85 |
|
| 86 |
Implement a ``clean()`` method on your ``Form`` when you must add custom |
| 87 |
validation for fields that are interdependent. See |
| 88 |
:ref:`validating-fields-with-clean` for example usage. |
| 89 |
|
| 90 |
.. method:: Form.is_valid() |
| 91 |
|
| 92 |
The primary task of a :class:`Form` object is to validate data. With a bound |
| 93 |
:class:`Form` instance, call the :meth:`~Form.is_valid` method to run validation |
| 94 |
and return a boolean designating whether the data was valid: |
| 95 |
|
| 96 |
.. code-block:: pycon |
| 97 |
|
| 98 |
>>> data = { |
| 99 |
... "subject": "hello", |
| 100 |
... "message": "Hi there", |
| 101 |
... "sender": "[email protected]", |
| 102 |
... "cc_myself": True, |
| 103 |
... } |
| 104 |
>>> f = ContactForm(data) |
| 105 |
>>> f.is_valid() |
| 106 |
True |
| 107 |
|
| 108 |
Let's try with some invalid data. In this case, ``subject`` is blank (an error, |
| 109 |
because all fields are required by default) and ``sender`` is not a valid |
| 110 |
email address: |
| 111 |
|
| 112 |
.. code-block:: pycon |
| 113 |
|
| 114 |
>>> data = { |
| 115 |
... "subject": "", |
| 116 |
... "message": "Hi there", |
| 117 |
... "sender": "invalid email address", |
| 118 |
... "cc_myself": True, |
| 119 |
... } |
| 120 |
>>> f = ContactForm(data) |
| 121 |
>>> f.is_valid() |
| 122 |
False |
| 123 |
|
| 124 |
.. attribute:: Form.errors |
| 125 |
|
| 126 |
Access the :attr:`~Form.errors` attribute to get a dictionary of error |
| 127 |
messages: |
| 128 |
|
| 129 |
.. code-block:: pycon |
| 130 |
|
| 131 |
>>> f.errors |
| 132 |
{'sender': ['Enter a valid email address.'], 'subject': ['This field is required.']} |
| 133 |
|
| 134 |
In this dictionary, the keys are the field names, and the values are lists of |
| 135 |
strings representing the error messages. The error messages are stored |
| 136 |
in lists because a field can have multiple error messages. |
| 137 |
|
| 138 |
You can access :attr:`~Form.errors` without having to call |
| 139 |
:meth:`~Form.is_valid` first. The form's data will be validated the first time |
| 140 |
either you call :meth:`~Form.is_valid` or access :attr:`~Form.errors`. |
| 141 |
|
| 142 |
The validation routines will only get called once, regardless of how many times |
| 143 |
you access :attr:`~Form.errors` or call :meth:`~Form.is_valid`. This means that |
| 144 |
if validation has side effects, those side effects will only be triggered once. |
| 145 |
|
| 146 |
.. method:: Form.errors.as_data() |
| 147 |
|
| 148 |
Returns a ``dict`` that maps fields to their original ``ValidationError`` |
| 149 |
instances. |
| 150 |
|
| 151 |
.. code-block:: pycon |
| 152 |
|
| 153 |
>>> f.errors.as_data() |
| 154 |
{'sender': [ValidationError(['Enter a valid email address.'])], |
| 155 |
'subject': [ValidationError(['This field is required.'])]} |
| 156 |
|
| 157 |
Use this method anytime you need to identify an error by its ``code``. This |
| 158 |
enables things like rewriting the error's message or writing custom logic in a |
| 159 |
view when a given error is present. It can also be used to serialize the errors |
| 160 |
in a custom format (e.g. XML); for instance, :meth:`~Form.errors.as_json()` |
| 161 |
relies on ``as_data()``. |
| 162 |
|
| 163 |
The need for the ``as_data()`` method is due to backwards compatibility. |
| 164 |
Previously ``ValidationError`` instances were lost as soon as their |
| 165 |
**rendered** error messages were added to the ``Form.errors`` dictionary. |
| 166 |
Ideally ``Form.errors`` would have stored ``ValidationError`` instances |
| 167 |
and methods with an ``as_`` prefix could render them, but it had to be done |
| 168 |
the other way around in order not to break code that expects rendered error |
| 169 |
messages in ``Form.errors``. |
| 170 |
|
| 171 |
.. method:: Form.errors.as_json(escape_html=False) |
| 172 |
|
| 173 |
Returns the errors serialized as JSON. |
| 174 |
|
| 175 |
.. code-block:: pycon |
| 176 |
|
| 177 |
>>> f.errors.as_json() |
| 178 |
{"sender": [{"message": "Enter a valid email address.", "code": "invalid"}], |
| 179 |
"subject": [{"message": "This field is required.", "code": "required"}]} |
| 180 |
|
| 181 |
By default, ``as_json()`` does not escape its output. If you are using it for |
| 182 |
something like AJAX requests to a form view where the client interprets the |
| 183 |
response and inserts errors into the page, you'll want to be sure to escape the |
| 184 |
results on the client-side to avoid the possibility of a cross-site scripting |
| 185 |
attack. You can do this in JavaScript with ``element.textContent = errorText`` |
| 186 |
or with jQuery's ``$(el).text(errorText)`` (rather than its ``.html()`` |
| 187 |
function). |
| 188 |
|
| 189 |
If for some reason you don't want to use client-side escaping, you can also |
| 190 |
set ``escape_html=True`` and error messages will be escaped so you can use them |
| 191 |
directly in HTML. |
| 192 |
|
| 193 |
.. method:: Form.errors.get_json_data(escape_html=False) |
| 194 |
|
| 195 |
Returns the errors as a dictionary suitable for serializing to JSON. |
| 196 |
:meth:`Form.errors.as_json()` returns serialized JSON, while this returns the |
| 197 |
error data before it's serialized. |
| 198 |
|
| 199 |
The ``escape_html`` parameter behaves as described in |
| 200 |
:meth:`Form.errors.as_json()`. |
| 201 |
|
| 202 |
.. method:: Form.add_error(field, error) |
| 203 |
|
| 204 |
This method allows adding errors to specific fields from within the |
| 205 |
``Form.clean()`` method, or from outside the form altogether; for instance |
| 206 |
from a view. |
| 207 |
|
| 208 |
The ``field`` argument is the name of the field to which the errors |
| 209 |
should be added. If its value is ``None`` the error will be treated as |
| 210 |
a non-field error as returned by :meth:`Form.non_field_errors() |
| 211 |
<django.forms.Form.non_field_errors>`. |
| 212 |
|
| 213 |
The ``error`` argument can be a string, or preferably an instance of |
| 214 |
``ValidationError``. See :ref:`raising-validation-error` for best practices |
| 215 |
when defining form errors. |
| 216 |
|
| 217 |
Note that ``Form.add_error()`` automatically removes the relevant field from |
| 218 |
``cleaned_data``. |
| 219 |
|
| 220 |
.. method:: Form.has_error(field, code=None) |
| 221 |
|
| 222 |
This method returns a boolean designating whether a field has an error with |
| 223 |
a specific error ``code``. If ``code`` is ``None``, it will return ``True`` |
| 224 |
if the field contains any errors at all. |
| 225 |
|
| 226 |
To check for non-field errors use |
| 227 |
:data:`~django.core.exceptions.NON_FIELD_ERRORS` as the ``field`` parameter. |
| 228 |
|
| 229 |
.. method:: Form.non_field_errors() |
| 230 |
|
| 231 |
This method returns the list of errors from :attr:`Form.errors |
| 232 |
<django.forms.Form.errors>` that aren't associated with a particular field. |
| 233 |
This includes ``ValidationError``\s that are raised in :meth:`Form.clean() |
| 234 |
<django.forms.Form.clean>` and errors added using :meth:`Form.add_error(None, |
| 235 |
"...") <django.forms.Form.add_error>`. |
| 236 |
|
| 237 |
Behavior of unbound forms |
| 238 |
------------------------- |
| 239 |
|
| 240 |
It's meaningless to validate a form with no data, but, for the record, here's |
| 241 |
what happens with unbound forms: |
| 242 |
|
| 243 |
.. code-block:: pycon |
| 244 |
|
| 245 |
>>> f = ContactForm() |
| 246 |
>>> f.is_valid() |
| 247 |
False |
| 248 |
>>> f.errors |
| 249 |
{} |
| 250 |
|
| 251 |
.. _ref-forms-initial-form-values: |
| 252 |
|
| 253 |
Initial form values |
| 254 |
=================== |
| 255 |
|
| 256 |
.. attribute:: Form.initial |
| 257 |
|
| 258 |
Use :attr:`~Form.initial` to declare the initial value of form fields at |
| 259 |
runtime. For example, you might want to fill in a ``username`` field with the |
| 260 |
username of the current session. |
| 261 |
|
| 262 |
To accomplish this, use the :attr:`~Form.initial` argument to a :class:`Form`. |
| 263 |
This argument, if given, should be a dictionary mapping field names to initial |
| 264 |
values. Only include the fields for which you're specifying an initial value; |
| 265 |
it's not necessary to include every field in your form. For example: |
| 266 |
|
| 267 |
.. code-block:: pycon |
| 268 |
|
| 269 |
>>> f = ContactForm(initial={"subject": "Hi there!"}) |
| 270 |
|
| 271 |
These values are only displayed for unbound forms, and they're not used as |
| 272 |
fallback values if a particular value isn't provided. |
| 273 |
|
| 274 |
If a :class:`~django.forms.Field` defines :attr:`~Field.initial` *and* you |
| 275 |
include :attr:`~Form.initial` when instantiating the ``Form``, then the latter |
| 276 |
``initial`` will have precedence. In this example, ``initial`` is provided both |
| 277 |
at the field level and at the form instance level, and the latter gets |
| 278 |
precedence: |
| 279 |
|
| 280 |
.. code-block:: pycon |
| 281 |
|
| 282 |
>>> from django import forms |
| 283 |
>>> class CommentForm(forms.Form): |
| 284 |
... name = forms.CharField(initial="class") |
| 285 |
... url = forms.URLField() |
| 286 |
... comment = forms.CharField() |
| 287 |
... |
| 288 |
>>> f = CommentForm(initial={"name": "instance"}, auto_id=False) |
| 289 |
>>> print(f) |
| 290 |
<div>Name:<input type="text" name="name" value="instance" required></div> |
| 291 |
<div>Url:<input type="url" name="url" required></div> |
| 292 |
<div>Comment:<input type="text" name="comment" required></div> |
| 293 |
|
| 294 |
.. method:: Form.get_initial_for_field(field, field_name) |
| 295 |
|
| 296 |
Returns the initial data for a form field. It retrieves the data from |
| 297 |
:attr:`Form.initial` if present, otherwise trying :attr:`Field.initial`. |
| 298 |
Callable values are evaluated. |
| 299 |
|
| 300 |
It is recommended to use :attr:`BoundField.initial` over |
| 301 |
:meth:`~Form.get_initial_for_field()` because ``BoundField.initial`` has a |
| 302 |
simpler interface. Also, unlike :meth:`~Form.get_initial_for_field()`, |
| 303 |
:attr:`BoundField.initial` caches its values. This is useful especially when |
| 304 |
dealing with callables whose return values can change (e.g. ``datetime.now`` or |
| 305 |
``uuid.uuid4``): |
| 306 |
|
| 307 |
.. code-block:: pycon |
| 308 |
|
| 309 |
>>> import uuid |
| 310 |
>>> class UUIDCommentForm(CommentForm): |
| 311 |
... identifier = forms.UUIDField(initial=uuid.uuid4) |
| 312 |
... |
| 313 |
>>> f = UUIDCommentForm() |
| 314 |
>>> f.get_initial_for_field(f.fields["identifier"], "identifier") |
| 315 |
UUID('972ca9e4-7bfe-4f5b-af7d-07b3aa306334') |
| 316 |
>>> f.get_initial_for_field(f.fields["identifier"], "identifier") |
| 317 |
UUID('1b411fab-844e-4dec-bd4f-e9b0495f04d0') |
| 318 |
>>> # Using BoundField.initial, for comparison |
| 319 |
>>> f["identifier"].initial |
| 320 |
UUID('28a09c59-5f00-4ed9-9179-a3b074fa9c30') |
| 321 |
>>> f["identifier"].initial |
| 322 |
UUID('28a09c59-5f00-4ed9-9179-a3b074fa9c30') |
| 323 |
|
| 324 |
Checking which form data has changed |
| 325 |
==================================== |
| 326 |
|
| 327 |
.. method:: Form.has_changed() |
| 328 |
|
| 329 |
Use the ``has_changed()`` method on your ``Form`` when you need to check if the |
| 330 |
form data has been changed from the initial data. |
| 331 |
|
| 332 |
.. code-block:: pycon |
| 333 |
|
| 334 |
>>> data = { |
| 335 |
... "subject": "hello", |
| 336 |
... "message": "Hi there", |
| 337 |
... "sender": "[email protected]", |
| 338 |
... "cc_myself": True, |
| 339 |
... } |
| 340 |
>>> f = ContactForm(data, initial=data) |
| 341 |
>>> f.has_changed() |
| 342 |
False |
| 343 |
|
| 344 |
When the form is submitted, we reconstruct it and provide the original data |
| 345 |
so that the comparison can be done: |
| 346 |
|
| 347 |
.. code-block:: pycon |
| 348 |
|
| 349 |
>>> f = ContactForm(request.POST, initial=data) |
| 350 |
>>> f.has_changed() |
| 351 |
|
| 352 |
``has_changed()`` will be ``True`` if the data from ``request.POST`` differs |
| 353 |
from what was provided in :attr:`~Form.initial` or ``False`` otherwise. The |
| 354 |
result is computed by calling :meth:`Field.has_changed` for each field in the |
| 355 |
form. |
| 356 |
|
| 357 |
.. attribute:: Form.changed_data |
| 358 |
|
| 359 |
The ``changed_data`` attribute returns a list of the names of the fields whose |
| 360 |
values in the form's bound data (usually ``request.POST``) differ from what was |
| 361 |
provided in :attr:`~Form.initial`. It returns an empty list if no data differs. |
| 362 |
|
| 363 |
.. code-block:: pycon |
| 364 |
|
| 365 |
>>> f = ContactForm(request.POST, initial=data) |
| 366 |
>>> if f.has_changed(): |
| 367 |
... print("The following fields changed: %s" % ", ".join(f.changed_data)) |
| 368 |
... |
| 369 |
>>> f.changed_data |
| 370 |
['subject', 'message'] |
| 371 |
|
| 372 |
Accessing the fields from the form |
| 373 |
================================== |
| 374 |
|
| 375 |
.. attribute:: Form.fields |
| 376 |
|
| 377 |
You can access the fields of :class:`Form` instance from its ``fields`` |
| 378 |
attribute: |
| 379 |
|
| 380 |
.. code-block:: pycon |
| 381 |
|
| 382 |
>>> for row in f.fields.values(): |
| 383 |
... print(row) |
| 384 |
... |
| 385 |
<django.forms.fields.CharField object at 0x7ffaac632510> |
| 386 |
<django.forms.fields.URLField object at 0x7ffaac632f90> |
| 387 |
<django.forms.fields.CharField object at 0x7ffaac3aa050> |
| 388 |
>>> f.fields["name"] |
| 389 |
<django.forms.fields.CharField object at 0x7ffaac6324d0> |
| 390 |
|
| 391 |
You can alter the field and :class:`.BoundField` of :class:`Form` instance to |
| 392 |
change the way it is presented in the form: |
| 393 |
|
| 394 |
.. code-block:: pycon |
| 395 |
|
| 396 |
>>> f.as_div().split("</div>")[0] |
| 397 |
'<div><label for="id_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_subject">' |
| 398 |
>>> f["subject"].label = "Topic" |
| 399 |
>>> f.as_div().split("</div>")[0] |
| 400 |
'<div><label for="id_subject">Topic:</label><input type="text" name="subject" maxlength="100" required id="id_subject">' |
| 401 |
|
| 402 |
Beware not to alter the ``base_fields`` attribute because this modification |
| 403 |
will influence all subsequent ``ContactForm`` instances within the same Python |
| 404 |
process: |
| 405 |
|
| 406 |
.. code-block:: pycon |
| 407 |
|
| 408 |
>>> f.base_fields["subject"].label_suffix = "?" |
| 409 |
>>> another_f = ContactForm(auto_id=False) |
| 410 |
>>> another_f.as_div().split("</div>")[0] |
| 411 |
'<div><label for="id_subject">Subject?</label><input type="text" name="subject" maxlength="100" required id="id_subject">' |
| 412 |
|
| 413 |
Accessing "clean" data |
| 414 |
====================== |
| 415 |
|
| 416 |
.. attribute:: Form.cleaned_data |
| 417 |
|
| 418 |
Each field in a :class:`Form` class is responsible not only for validating |
| 419 |
data, but also for "cleaning" it -- normalizing it to a consistent format. This |
| 420 |
is a nice feature, because it allows data for a particular field to be input in |
| 421 |
a variety of ways, always resulting in consistent output. |
| 422 |
|
| 423 |
For example, :class:`~django.forms.DateField` normalizes input into a |
| 424 |
Python ``datetime.date`` object. Regardless of whether you pass it a string in |
| 425 |
the format ``'1994-07-15'``, a ``datetime.date`` object, or a number of other |
| 426 |
formats, ``DateField`` will always normalize it to a ``datetime.date`` object |
| 427 |
as long as it's valid. |
| 428 |
|
| 429 |
Once you've created a :class:`~Form` instance with a set of data and validated |
| 430 |
it, you can access the clean data via its ``cleaned_data`` attribute: |
| 431 |
|
| 432 |
.. code-block:: pycon |
| 433 |
|
| 434 |
>>> data = { |
| 435 |
... "subject": "hello", |
| 436 |
... "message": "Hi there", |
| 437 |
... "sender": "[email protected]", |
| 438 |
... "cc_myself": True, |
| 439 |
... } |
| 440 |
>>> f = ContactForm(data) |
| 441 |
>>> f.is_valid() |
| 442 |
True |
| 443 |
>>> f.cleaned_data |
| 444 |
{'cc_myself': True, 'message': 'Hi there', 'sender': '[email protected]', 'subject': 'hello'} |
| 445 |
|
| 446 |
Note that any text-based field -- such as ``CharField`` or ``EmailField`` -- |
| 447 |
always cleans the input into a string. We'll cover the encoding implications |
| 448 |
later in this document. |
| 449 |
|
| 450 |
If your data does *not* validate, the ``cleaned_data`` dictionary contains |
| 451 |
only the valid fields: |
| 452 |
|
| 453 |
.. code-block:: pycon |
| 454 |
|
| 455 |
>>> data = { |
| 456 |
... "subject": "", |
| 457 |
... "message": "Hi there", |
| 458 |
... "sender": "invalid email address", |
| 459 |
... "cc_myself": True, |
| 460 |
... } |
| 461 |
>>> f = ContactForm(data) |
| 462 |
>>> f.is_valid() |
| 463 |
False |
| 464 |
>>> f.cleaned_data |
| 465 |
{'cc_myself': True, 'message': 'Hi there'} |
| 466 |
|
| 467 |
``cleaned_data`` will always *only* contain a key for fields defined in the |
| 468 |
``Form``, even if you pass extra data when you define the ``Form``. In this |
| 469 |
example, we pass a bunch of extra fields to the ``ContactForm`` constructor, |
| 470 |
but ``cleaned_data`` contains only the form's fields: |
| 471 |
|
| 472 |
.. code-block:: pycon |
| 473 |
|
| 474 |
>>> data = { |
| 475 |
... "subject": "hello", |
| 476 |
... "message": "Hi there", |
| 477 |
... "sender": "[email protected]", |
| 478 |
... "cc_myself": True, |
| 479 |
... "extra_field_1": "foo", |
| 480 |
... "extra_field_2": "bar", |
| 481 |
... "extra_field_3": "baz", |
| 482 |
... } |
| 483 |
>>> f = ContactForm(data) |
| 484 |
>>> f.is_valid() |
| 485 |
True |
| 486 |
>>> f.cleaned_data # Doesn't contain extra_field_1, etc. |
| 487 |
{'cc_myself': True, 'message': 'Hi there', 'sender': '[email protected]', 'subject': 'hello'} |
| 488 |
|
| 489 |
When the ``Form`` is valid, ``cleaned_data`` will include a key and value for |
| 490 |
*all* its fields, even if the data didn't include a value for some optional |
| 491 |
fields. In this example, the data dictionary doesn't include a value for the |
| 492 |
``nick_name`` field, but ``cleaned_data`` includes it, with an empty value: |
| 493 |
|
| 494 |
.. code-block:: pycon |
| 495 |
|
| 496 |
>>> from django import forms |
| 497 |
>>> class OptionalPersonForm(forms.Form): |
| 498 |
... first_name = forms.CharField() |
| 499 |
... last_name = forms.CharField() |
| 500 |
... nick_name = forms.CharField(required=False) |
| 501 |
... |
| 502 |
>>> data = {"first_name": "John", "last_name": "Lennon"} |
| 503 |
>>> f = OptionalPersonForm(data) |
| 504 |
>>> f.is_valid() |
| 505 |
True |
| 506 |
>>> f.cleaned_data |
| 507 |
{'nick_name': '', 'first_name': 'John', 'last_name': 'Lennon'} |
| 508 |
|
| 509 |
In this above example, the ``cleaned_data`` value for ``nick_name`` is set to an |
| 510 |
empty string, because ``nick_name`` is ``CharField``, and ``CharField``\s treat |
| 511 |
empty values as an empty string. Each field type knows what its "blank" value |
| 512 |
is -- e.g., for ``DateField``, it's ``None`` instead of the empty string. For |
| 513 |
full details on each field's behavior in this case, see the "Empty value" note |
| 514 |
for each field in the :ref:`built-in-fields` section below. |
| 515 |
|
| 516 |
You can write code to perform validation for particular form fields (based on |
| 517 |
their name) or for the form as a whole (considering combinations of various |
| 518 |
fields). More information about this is in :doc:`/ref/forms/validation`. |
| 519 |
|
| 520 |
.. _ref-forms-api-outputting-html: |
| 521 |
|
| 522 |
Outputting forms as HTML |
| 523 |
======================== |
| 524 |
|
| 525 |
The second task of a ``Form`` object is to render itself as HTML. To do so, |
| 526 |
``print`` it: |
| 527 |
|
| 528 |
.. code-block:: pycon |
| 529 |
|
| 530 |
>>> f = ContactForm() |
| 531 |
>>> print(f) |
| 532 |
<div><label for="id_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_subject"></div> |
| 533 |
<div><label for="id_message">Message:</label><input type="text" name="message" required id="id_message"></div> |
| 534 |
<div><label for="id_sender">Sender:</label><input type="email" name="sender" required id="id_sender"></div> |
| 535 |
<div><label for="id_cc_myself">Cc myself:</label><input type="checkbox" name="cc_myself" id="id_cc_myself"></div> |
| 536 |
|
| 537 |
If the form is bound to data, the HTML output will include that data |
| 538 |
appropriately. For example, if a field is represented by an |
| 539 |
``<input type="text">``, the data will be in the ``value`` attribute. If a |
| 540 |
field is represented by an ``<input type="checkbox">``, then that HTML will |
| 541 |
include ``checked`` if appropriate: |
| 542 |
|
| 543 |
.. code-block:: pycon |
| 544 |
|
| 545 |
>>> data = { |
| 546 |
... "subject": "hello", |
| 547 |
... "message": "Hi there", |
| 548 |
... "sender": "[email protected]", |
| 549 |
... "cc_myself": True, |
| 550 |
... } |
| 551 |
>>> f = ContactForm(data) |
| 552 |
>>> print(f) |
| 553 |
<div><label for="id_subject">Subject:</label><input type="text" name="subject" value="hello" maxlength="100" required id="id_subject"></div> |
| 554 |
<div><label for="id_message">Message:</label><input type="text" name="message" value="Hi there" required id="id_message"></div> |
| 555 |
<div><label for="id_sender">Sender:</label><input type="email" name="sender" value="[email protected]" required id="id_sender"></div> |
| 556 |
<div><label for="id_cc_myself">Cc myself:</label><input type="checkbox" name="cc_myself" id="id_cc_myself" checked></div> |
| 557 |
|
| 558 |
This default output wraps each field with a ``<div>``. Notice the following: |
| 559 |
|
| 560 |
* For flexibility, the output does *not* include the ``<form>`` and ``</form>`` |
| 561 |
tags or an ``<input type="submit">`` tag. It's your job to do that. |
| 562 |
|
| 563 |
* Each field type has a default HTML representation. ``CharField`` is |
| 564 |
represented by an ``<input type="text">`` and ``EmailField`` by an |
| 565 |
``<input type="email">``. ``BooleanField(null=False)`` is represented by an |
| 566 |
``<input type="checkbox">``. Note these are merely sensible defaults; you can |
| 567 |
specify which HTML to use for a given field by using widgets, which we'll |
| 568 |
explain shortly. |
| 569 |
|
| 570 |
* The HTML ``name`` for each tag is taken directly from its attribute name |
| 571 |
in the ``ContactForm`` class. |
| 572 |
|
| 573 |
* The text label for each field -- e.g. ``'Subject:'``, ``'Message:'`` and |
| 574 |
``'Cc myself:'`` is generated from the field name by converting all |
| 575 |
underscores to spaces and upper-casing the first letter. Again, note |
| 576 |
these are merely sensible defaults; you can also specify labels manually. |
| 577 |
|
| 578 |
* Each text label is surrounded in an HTML ``<label>`` tag, which points |
| 579 |
to the appropriate form field via its ``id``. Its ``id``, in turn, is |
| 580 |
generated by prepending ``'id_'`` to the field name. The ``id`` |
| 581 |
attributes and ``<label>`` tags are included in the output by default, to |
| 582 |
follow best practices, but you can change that behavior. |
| 583 |
|
| 584 |
* The output uses HTML5 syntax, targeting ``<!DOCTYPE html>``. For example, |
| 585 |
it uses boolean attributes such as ``checked`` rather than the XHTML style |
| 586 |
of ``checked='checked'``. |
| 587 |
|
| 588 |
Although ``<div>`` output is the default output style when you ``print`` a form |
| 589 |
you can customize the output by using your own form template which can be set |
| 590 |
site-wide, per-form, or per-instance. See :ref:`reusable-form-templates`. |
| 591 |
|
| 592 |
Default rendering |
| 593 |
----------------- |
| 594 |
|
| 595 |
The default rendering when you ``print`` a form uses the following methods and |
| 596 |
attributes. |
| 597 |
|
| 598 |
``template_name`` |
| 599 |
~~~~~~~~~~~~~~~~~ |
| 600 |
|
| 601 |
.. attribute:: Form.template_name |
| 602 |
|
| 603 |
The name of the template rendered if the form is cast into a string, e.g. via |
| 604 |
``print(form)`` or in a template via ``{{ form }}``. |
| 605 |
|
| 606 |
By default, a property returning the value of the renderer's |
| 607 |
:attr:`~django.forms.renderers.BaseRenderer.form_template_name`. You may set it |
| 608 |
as a string template name in order to override that for a particular form |
| 609 |
class. |
| 610 |
|
| 611 |
``render()`` |
| 612 |
~~~~~~~~~~~~ |
| 613 |
|
| 614 |
.. method:: Form.render(template_name=None, context=None, renderer=None) |
| 615 |
|
| 616 |
The render method is called by ``__str__`` as well as the :meth:`.Form.as_div`, |
| 617 |
:meth:`.Form.as_table`, :meth:`.Form.as_p`, and :meth:`.Form.as_ul` methods. |
| 618 |
All arguments are optional and default to: |
| 619 |
|
| 620 |
* ``template_name``: :attr:`.Form.template_name` |
| 621 |
* ``context``: Value returned by :meth:`.Form.get_context` |
| 622 |
* ``renderer``: Value returned by :attr:`.Form.default_renderer` |
| 623 |
|
| 624 |
By passing ``template_name`` you can customize the template used for just a |
| 625 |
single call. |
| 626 |
|
| 627 |
``get_context()`` |
| 628 |
~~~~~~~~~~~~~~~~~ |
| 629 |
|
| 630 |
.. method:: Form.get_context() |
| 631 |
|
| 632 |
Return the template context for rendering the form. |
| 633 |
|
| 634 |
The available context is: |
| 635 |
|
| 636 |
* ``form``: The bound form. |
| 637 |
* ``fields``: All bound fields, except the hidden fields. |
| 638 |
* ``hidden_fields``: All hidden bound fields. |
| 639 |
* ``errors``: All non field related or hidden field related form errors. |
| 640 |
|
| 641 |
``template_name_label`` |
| 642 |
~~~~~~~~~~~~~~~~~~~~~~~ |
| 643 |
|
| 644 |
.. attribute:: Form.template_name_label |
| 645 |
|
| 646 |
The template used to render a field's ``<label>``, used when calling |
| 647 |
:meth:`BoundField.label_tag`/:meth:`~BoundField.legend_tag`. Can be changed per |
| 648 |
form by overriding this attribute or more generally by overriding the default |
| 649 |
template, see also :ref:`overriding-built-in-form-templates`. |
| 650 |
|
| 651 |
Output styles |
| 652 |
------------- |
| 653 |
|
| 654 |
The recommended approach for changing form output style is to set a custom form |
| 655 |
template either site-wide, per-form, or per-instance. See |
| 656 |
:ref:`reusable-form-templates` for examples. |
| 657 |
|
| 658 |
The following helper functions are provided for backward compatibility and are |
| 659 |
a proxy to :meth:`Form.render` passing a particular ``template_name`` value. |
| 660 |
|
| 661 |
.. note:: |
| 662 |
|
| 663 |
Of the framework provided templates and output styles, the default |
| 664 |
``as_div()`` is recommended over the ``as_p()``, ``as_table()``, and |
| 665 |
``as_ul()`` versions as the template implements ``<fieldset>`` and |
| 666 |
``<legend>`` to group related inputs and is easier for screen reader users |
| 667 |
to navigate. |
| 668 |
|
| 669 |
Each helper pairs a form method with an attribute giving the appropriate |
| 670 |
template name. |
| 671 |
|
| 672 |
``as_div()`` |
| 673 |
~~~~~~~~~~~~ |
| 674 |
|
| 675 |
.. attribute:: Form.template_name_div |
| 676 |
|
| 677 |
The template used by ``as_div()``. Default: ``'django/forms/div.html'``. |
| 678 |
|
| 679 |
.. method:: Form.as_div() |
| 680 |
|
| 681 |
``as_div()`` renders the form as a series of ``<div>`` elements, with each |
| 682 |
``<div>`` containing one field, such as: |
| 683 |
|
| 684 |
.. code-block:: pycon |
| 685 |
|
| 686 |
>>> f = ContactForm() |
| 687 |
>>> f.as_div() |
| 688 |
|
| 689 |
… gives HTML like: |
| 690 |
|
| 691 |
.. code-block:: html |
| 692 |
|
| 693 |
<div> |
| 694 |
<label for="id_subject">Subject:</label> |
| 695 |
<input type="text" name="subject" maxlength="100" required id="id_subject"> |
| 696 |
</div> |
| 697 |
<div> |
| 698 |
<label for="id_message">Message:</label> |
| 699 |
<input type="text" name="message" required id="id_message"> |
| 700 |
</div> |
| 701 |
<div> |
| 702 |
<label for="id_sender">Sender:</label> |
| 703 |
<input type="email" name="sender" required id="id_sender"> |
| 704 |
</div> |
| 705 |
<div> |
| 706 |
<label for="id_cc_myself">Cc myself:</label> |
| 707 |
<input type="checkbox" name="cc_myself" id="id_cc_myself"> |
| 708 |
</div> |
| 709 |
|
| 710 |
``as_p()`` |
| 711 |
~~~~~~~~~~ |
| 712 |
|
| 713 |
.. attribute:: Form.template_name_p |
| 714 |
|
| 715 |
The template used by ``as_p()``. Default: ``'django/forms/p.html'``. |
| 716 |
|
| 717 |
.. method:: Form.as_p() |
| 718 |
|
| 719 |
``as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>`` |
| 720 |
containing one field: |
| 721 |
|
| 722 |
.. code-block:: pycon |
| 723 |
|
| 724 |
>>> f = ContactForm() |
| 725 |
>>> f.as_p() |
| 726 |
'<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></p>\n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></p>\n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" required></p>\n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></p>' |
| 727 |
>>> print(f.as_p()) |
| 728 |
<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></p> |
| 729 |
<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></p> |
| 730 |
<p><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></p> |
| 731 |
<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></p> |
| 732 |
|
| 733 |
``as_ul()`` |
| 734 |
~~~~~~~~~~~ |
| 735 |
|
| 736 |
.. attribute:: Form.template_name_ul |
| 737 |
|
| 738 |
The template used by ``as_ul()``. Default: ``'django/forms/ul.html'``. |
| 739 |
|
| 740 |
.. method:: Form.as_ul() |
| 741 |
|
| 742 |
``as_ul()`` renders the form as a series of ``<li>`` tags, with each ``<li>`` |
| 743 |
containing one field. It does *not* include the ``<ul>`` or ``</ul>``, so that |
| 744 |
you can specify any HTML attributes on the ``<ul>`` for flexibility: |
| 745 |
|
| 746 |
.. code-block:: pycon |
| 747 |
|
| 748 |
>>> f = ContactForm() |
| 749 |
>>> f.as_ul() |
| 750 |
'<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></li>\n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></li>\n<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></li>\n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></li>' |
| 751 |
>>> print(f.as_ul()) |
| 752 |
<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></li> |
| 753 |
<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></li> |
| 754 |
<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></li> |
| 755 |
<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></li> |
| 756 |
|
| 757 |
``as_table()`` |
| 758 |
~~~~~~~~~~~~~~ |
| 759 |
|
| 760 |
.. attribute:: Form.template_name_table |
| 761 |
|
| 762 |
The template used by ``as_table()``. Default: ``'django/forms/table.html'``. |
| 763 |
|
| 764 |
.. method:: Form.as_table() |
| 765 |
|
| 766 |
``as_table()`` renders the form as an HTML ``<table>``: |
| 767 |
|
| 768 |
.. code-block:: pycon |
| 769 |
|
| 770 |
>>> f = ContactForm() |
| 771 |
>>> f.as_table() |
| 772 |
'<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr>\n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></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>' |
| 773 |
>>> print(f.as_table()) |
| 774 |
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr> |
| 775 |
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr> |
| 776 |
<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr> |
| 777 |
<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr> |
| 778 |
|
| 779 |
.. _ref-forms-api-styling-form-rows: |
| 780 |
|
| 781 |
Styling required or erroneous form rows |
| 782 |
--------------------------------------- |
| 783 |
|
| 784 |
.. attribute:: Form.error_css_class |
| 785 |
.. attribute:: Form.required_css_class |
| 786 |
|
| 787 |
It's pretty common to style form rows and fields that are required or have |
| 788 |
errors. For example, you might want to present required form rows in bold and |
| 789 |
highlight errors in red. |
| 790 |
|
| 791 |
The :class:`Form` class has a couple of hooks you can use to add ``class`` |
| 792 |
attributes to required rows or to rows with errors: set the |
| 793 |
:attr:`Form.error_css_class` and/or :attr:`Form.required_css_class` |
| 794 |
attributes:: |
| 795 |
|
| 796 |
from django import forms |
| 797 |
|
| 798 |
|
| 799 |
class ContactForm(forms.Form): |
| 800 |
error_css_class = "error" |
| 801 |
required_css_class = "required" |
| 802 |
|
| 803 |
# ... and the rest of your fields here |
| 804 |
|
| 805 |
Once you've done that, rows will be given ``"error"`` and/or ``"required"`` |
| 806 |
classes, as needed. The HTML will look something like: |
| 807 |
|
| 808 |
.. code-block:: pycon |
| 809 |
|
| 810 |
>>> f = ContactForm(data) |
| 811 |
>>> print(f) |
| 812 |
<div class="required"><label for="id_subject" class="required">Subject:</label> ... |
| 813 |
<div class="required"><label for="id_message" class="required">Message:</label> ... |
| 814 |
<div class="required"><label for="id_sender" class="required">Sender:</label> ... |
| 815 |
<div><label for="id_cc_myself">Cc myself:</label> ... |
| 816 |
>>> f["subject"].label_tag() |
| 817 |
<label class="required" for="id_subject">Subject:</label> |
| 818 |
>>> f["subject"].legend_tag() |
| 819 |
<legend class="required" for="id_subject">Subject:</legend> |
| 820 |
>>> f["subject"].label_tag(attrs={"class": "foo"}) |
| 821 |
<label for="id_subject" class="foo required">Subject:</label> |
| 822 |
>>> f["subject"].legend_tag(attrs={"class": "foo"}) |
| 823 |
<legend for="id_subject" class="foo required">Subject:</legend> |
| 824 |
|
| 825 |
You may further modify the rendering of form rows by using a |
| 826 |
:ref:`custom BoundField <custom-boundfield>`. |
| 827 |
|
| 828 |
.. _ref-forms-api-configuring-label: |
| 829 |
|
| 830 |
Configuring form elements' HTML ``id`` attributes and ``<label>`` tags |
| 831 |
---------------------------------------------------------------------- |
| 832 |
|
| 833 |
.. attribute:: Form.auto_id |
| 834 |
|
| 835 |
By default, the form rendering methods include: |
| 836 |
|
| 837 |
* HTML ``id`` attributes on the form elements. |
| 838 |
|
| 839 |
* The corresponding ``<label>`` tags around the labels. An HTML ``<label>`` tag |
| 840 |
designates which label text is associated with which form element. This small |
| 841 |
enhancement makes forms more usable and more accessible to assistive devices. |
| 842 |
It's always a good idea to use ``<label>`` tags. |
| 843 |
|
| 844 |
The ``id`` attribute values are generated by prepending ``id_`` to the form |
| 845 |
field names. This behavior is configurable, though, if you want to change the |
| 846 |
``id`` convention or remove HTML ``id`` attributes and ``<label>`` tags |
| 847 |
entirely. |
| 848 |
|
| 849 |
Use the ``auto_id`` argument to the ``Form`` constructor to control the ``id`` |
| 850 |
and label behavior. This argument must be ``True``, ``False`` or a string. |
| 851 |
|
| 852 |
If ``auto_id`` is ``False``, then the form output will not include ``<label>`` |
| 853 |
tags nor ``id`` attributes: |
| 854 |
|
| 855 |
.. code-block:: pycon |
| 856 |
|
| 857 |
>>> f = ContactForm(auto_id=False) |
| 858 |
>>> print(f) |
| 859 |
<div>Subject:<input type="text" name="subject" maxlength="100" required></div> |
| 860 |
<div>Message:<textarea name="message" cols="40" rows="10" required></textarea></div> |
| 861 |
<div>Sender:<input type="email" name="sender" required></div> |
| 862 |
<div>Cc myself:<input type="checkbox" name="cc_myself"></div> |
| 863 |
|
| 864 |
If ``auto_id`` is set to ``True``, then the form output *will* include |
| 865 |
``<label>`` tags and will use the field name as its ``id`` for each form |
| 866 |
field: |
| 867 |
|
| 868 |
.. code-block:: pycon |
| 869 |
|
| 870 |
>>> f = ContactForm(auto_id=True) |
| 871 |
>>> print(f) |
| 872 |
<div><label for="subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="subject"></div> |
| 873 |
<div><label for="message">Message:</label><textarea name="message" cols="40" rows="10" required id="message"></textarea></div> |
| 874 |
<div><label for="sender">Sender:</label><input type="email" name="sender" required id="sender"></div> |
| 875 |
<div><label for="cc_myself">Cc myself:</label><input type="checkbox" name="cc_myself" id="cc_myself"></div> |
| 876 |
|
| 877 |
If ``auto_id`` is set to a string containing the format character ``'%s'``, |
| 878 |
then the form output will include ``<label>`` tags, and will generate ``id`` |
| 879 |
attributes based on the format string. For example, for a format string |
| 880 |
``'field_%s'``, a field named ``subject`` will get the ``id`` value |
| 881 |
``'field_subject'``. Continuing our example: |
| 882 |
|
| 883 |
.. code-block:: pycon |
| 884 |
|
| 885 |
>>> f = ContactForm(auto_id="id_for_%s") |
| 886 |
>>> print(f) |
| 887 |
<div><label for="id_for_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_for_subject"></div> |
| 888 |
<div><label for="id_for_message">Message:</label><textarea name="message" cols="40" rows="10" required id="id_for_message"></textarea></div> |
| 889 |
<div><label for="id_for_sender">Sender:</label><input type="email" name="sender" required id="id_for_sender"></div> |
| 890 |
<div><label for="id_for_cc_myself">Cc myself:</label><input type="checkbox" name="cc_myself" id="id_for_cc_myself"></div> |
| 891 |
|
| 892 |
If ``auto_id`` is set to any other true value -- such as a string that doesn't |
| 893 |
include ``%s`` -- then the library will act as if ``auto_id`` is ``True``. |
| 894 |
|
| 895 |
By default, ``auto_id`` is set to the string ``'id_%s'``. |
| 896 |
|
| 897 |
.. attribute:: Form.label_suffix |
| 898 |
|
| 899 |
A translatable string (defaults to a colon (``:``) in English) that will be |
| 900 |
appended after any label name when a form is rendered. |
| 901 |
|
| 902 |
It's possible to customize that character, or omit it entirely, using the |
| 903 |
``label_suffix`` parameter: |
| 904 |
|
| 905 |
.. code-block:: pycon |
| 906 |
|
| 907 |
>>> f = ContactForm(auto_id="id_for_%s", label_suffix="") |
| 908 |
>>> print(f) |
| 909 |
<div><label for="id_for_subject">Subject</label><input type="text" name="subject" maxlength="100" required id="id_for_subject"></div> |
| 910 |
<div><label for="id_for_message">Message</label><textarea name="message" cols="40" rows="10" required id="id_for_message"></textarea></div> |
| 911 |
<div><label for="id_for_sender">Sender</label><input type="email" name="sender" required id="id_for_sender"></div> |
| 912 |
<div><label for="id_for_cc_myself">Cc myself</label><input type="checkbox" name="cc_myself" id="id_for_cc_myself"></div> |
| 913 |
>>> f = ContactForm(auto_id="id_for_%s", label_suffix=" ->") |
| 914 |
>>> print(f) |
| 915 |
<div><label for="id_for_subject">Subject -></label><input type="text" name="subject" maxlength="100" required id="id_for_subject"></div> |
| 916 |
<div><label for="id_for_message">Message -></label><textarea name="message" cols="40" rows="10" required id="id_for_message"></textarea></div> |
| 917 |
<div><label for="id_for_sender">Sender -></label><input type="email" name="sender" required id="id_for_sender"></div> |
| 918 |
<div><label for="id_for_cc_myself">Cc myself -></label><input type="checkbox" name="cc_myself" id="id_for_cc_myself"></div> |
| 919 |
|
| 920 |
Note that the label suffix is added only if the last character of the |
| 921 |
label isn't a punctuation character (in English, those are ``.``, ``!``, ``?`` |
| 922 |
or ``:``). |
| 923 |
|
| 924 |
Fields can also define their own :attr:`~django.forms.Field.label_suffix`. |
| 925 |
This will take precedence over :attr:`Form.label_suffix |
| 926 |
<django.forms.Form.label_suffix>`. The suffix can also be overridden at runtime |
| 927 |
using the ``label_suffix`` parameter to |
| 928 |
:meth:`~django.forms.BoundField.label_tag`/ |
| 929 |
:meth:`~django.forms.BoundField.legend_tag`. |
| 930 |
|
| 931 |
.. attribute:: Form.use_required_attribute |
| 932 |
|
| 933 |
When set to ``True`` (the default), required form fields will have the |
| 934 |
``required`` HTML attribute. |
| 935 |
|
| 936 |
:doc:`Formsets </topics/forms/formsets>` instantiate forms with |
| 937 |
``use_required_attribute=False`` to avoid incorrect browser validation when |
| 938 |
adding and deleting forms from a formset. |
| 939 |
|
| 940 |
Configuring the rendering of a form's widgets |
| 941 |
--------------------------------------------- |
| 942 |
|
| 943 |
.. attribute:: Form.default_renderer |
| 944 |
|
| 945 |
Specifies the :doc:`renderer <renderers>` to use for the form. Defaults to |
| 946 |
``None`` which means to use the default renderer specified by the |
| 947 |
:setting:`FORM_RENDERER` setting. |
| 948 |
|
| 949 |
You can set this as a class attribute when declaring your form or use the |
| 950 |
``renderer`` argument to ``Form.__init__()``. For example:: |
| 951 |
|
| 952 |
from django import forms |
| 953 |
|
| 954 |
|
| 955 |
class MyForm(forms.Form): |
| 956 |
default_renderer = MyRenderer() |
| 957 |
|
| 958 |
or:: |
| 959 |
|
| 960 |
form = MyForm(renderer=MyRenderer()) |
| 961 |
|
| 962 |
Notes on field ordering |
| 963 |
----------------------- |
| 964 |
|
| 965 |
In the ``as_p()``, ``as_ul()`` and ``as_table()`` shortcuts, the fields are |
| 966 |
displayed in the order in which you define them in your form class. For |
| 967 |
example, in the ``ContactForm`` example, the fields are defined in the order |
| 968 |
``subject``, ``message``, ``sender``, ``cc_myself``. To reorder the HTML |
| 969 |
output, change the order in which those fields are listed in the class. |
| 970 |
|
| 971 |
There are several other ways to customize the order: |
| 972 |
|
| 973 |
.. attribute:: Form.field_order |
| 974 |
|
| 975 |
By default ``Form.field_order=None``, which retains the order in which you |
| 976 |
define the fields in your form class. If ``field_order`` is a list of field |
| 977 |
names, the fields are ordered as specified by the list and remaining fields are |
| 978 |
appended according to the default order. Unknown field names in the list are |
| 979 |
ignored. This makes it possible to disable a field in a subclass by setting it |
| 980 |
to ``None`` without having to redefine ordering. |
| 981 |
|
| 982 |
You can also use the ``Form.field_order`` argument to a :class:`Form` to |
| 983 |
override the field order. If a :class:`~django.forms.Form` defines |
| 984 |
:attr:`~Form.field_order` *and* you include ``field_order`` when instantiating |
| 985 |
the ``Form``, then the latter ``field_order`` will have precedence. |
| 986 |
|
| 987 |
.. method:: Form.order_fields(field_order) |
| 988 |
|
| 989 |
You may rearrange the fields any time using ``order_fields()`` with a list of |
| 990 |
field names as in :attr:`~django.forms.Form.field_order`. |
| 991 |
|
| 992 |
.. _form-error-display: |
| 993 |
|
| 994 |
How errors are displayed |
| 995 |
------------------------ |
| 996 |
|
| 997 |
If you render a bound ``Form`` object, the act of rendering will automatically |
| 998 |
run the form's validation if it hasn't already happened, and the HTML output |
| 999 |
will include the validation errors as a ``<ul class="errorlist">``. |
| 1000 |
|
| 1001 |
The following: |
| 1002 |
|
| 1003 |
.. code-block:: pycon |
| 1004 |
|
| 1005 |
>>> data = { |
| 1006 |
... "subject": "", |
| 1007 |
... "message": "Hi there", |
| 1008 |
... "sender": "invalid email address", |
| 1009 |
... "cc_myself": True, |
| 1010 |
... } |
| 1011 |
>>> ContactForm(data).as_div() |
| 1012 |
|
| 1013 |
… gives HTML like: |
| 1014 |
|
| 1015 |
.. code-block:: html |
| 1016 |
|
| 1017 |
<div> |
| 1018 |
<label for="id_subject">Subject:</label> |
| 1019 |
<ul class="errorlist" id="id_subject_error"><li>This field is required.</li></ul> |
| 1020 |
<input type="text" name="subject" maxlength="100" required aria-invalid="true" aria-describedby="id_subject_error" id="id_subject"> |
| 1021 |
</div> |
| 1022 |
<div> |
| 1023 |
<label for="id_message">Message:</label> |
| 1024 |
<textarea name="message" cols="40" rows="10" required id="id_message">Hi there</textarea> |
| 1025 |
</div> |
| 1026 |
<div> |
| 1027 |
<label for="id_sender">Sender:</label> |
| 1028 |
<ul class="errorlist" id="id_sender_error"><li>Enter a valid email address.</li></ul> |
| 1029 |
<input type="email" name="sender" value="invalid email address" maxlength="320" required aria-invalid="true" aria-describedby="id_sender_error" id="id_sender"> |
| 1030 |
</div> |
| 1031 |
<div> |
| 1032 |
<label for="id_cc_myself">Cc myself:</label> |
| 1033 |
<input type="checkbox" name="cc_myself" id="id_cc_myself" checked> |
| 1034 |
</div> |
| 1035 |
|
| 1036 |
Django's default form templates will associate validation errors with their |
| 1037 |
input by using the ``aria-describedby`` HTML attribute when the field has an |
| 1038 |
``auto_id`` and a custom ``aria-describedby`` is not provided. If a custom |
| 1039 |
``aria-describedby`` is set when defining the widget this will override the |
| 1040 |
default value. |
| 1041 |
|
| 1042 |
If the widget is rendered in a ``<fieldset>`` then ``aria-describedby`` is |
| 1043 |
added to this element, otherwise it is added to the widget's HTML element (e.g. |
| 1044 |
``<input>``). |
| 1045 |
|
| 1046 |
.. versionchanged:: 5.2 |
| 1047 |
|
| 1048 |
``aria-describedby`` was added to associate errors with its input. |
| 1049 |
|
| 1050 |
.. _ref-forms-error-list-format: |
| 1051 |
|
| 1052 |
Customizing the error list format |
| 1053 |
--------------------------------- |
| 1054 |
|
| 1055 |
.. class:: ErrorList(initlist=None, error_class=None, renderer=None, field_id=None) |
| 1056 |
|
| 1057 |
By default, forms use ``django.forms.utils.ErrorList`` to format validation |
| 1058 |
errors. ``ErrorList`` is a list like object where ``initlist`` is the |
| 1059 |
list of errors. In addition this class has the following attributes and |
| 1060 |
methods. |
| 1061 |
|
| 1062 |
.. versionchanged:: 5.2 |
| 1063 |
|
| 1064 |
The ``field_id`` argument was added. |
| 1065 |
|
| 1066 |
.. attribute:: error_class |
| 1067 |
|
| 1068 |
The CSS classes to be used when rendering the error list. Any provided |
| 1069 |
classes are added to the default ``errorlist`` class. |
| 1070 |
|
| 1071 |
.. attribute:: renderer |
| 1072 |
|
| 1073 |
Specifies the :doc:`renderer <renderers>` to use for ``ErrorList``. |
| 1074 |
Defaults to ``None`` which means to use the default renderer |
| 1075 |
specified by the :setting:`FORM_RENDERER` setting. |
| 1076 |
|
| 1077 |
.. attribute:: field_id |
| 1078 |
|
| 1079 |
.. versionadded:: 5.2 |
| 1080 |
|
| 1081 |
An ``id`` for the field for which the errors relate. This allows an |
| 1082 |
HTML ``id`` attribute to be added in the error template and is useful |
| 1083 |
to associate the errors with the field. The default template uses the |
| 1084 |
format ``id="{{ field_id }}_error"`` and a value is provided by |
| 1085 |
:meth:`.Form.add_error` using the field's :attr:`~.BoundField.auto_id`. |
| 1086 |
|
| 1087 |
.. attribute:: template_name |
| 1088 |
|
| 1089 |
The name of the template used when calling ``__str__`` or |
| 1090 |
:meth:`render`. By default this is |
| 1091 |
``'django/forms/errors/list/default.html'`` which is a proxy for the |
| 1092 |
``'ul.html'`` template. |
| 1093 |
|
| 1094 |
.. attribute:: template_name_text |
| 1095 |
|
| 1096 |
The name of the template used when calling :meth:`.as_text`. By default |
| 1097 |
this is ``'django/forms/errors/list/text.html'``. This template renders |
| 1098 |
the errors as a list of bullet points. |
| 1099 |
|
| 1100 |
.. attribute:: template_name_ul |
| 1101 |
|
| 1102 |
The name of the template used when calling :meth:`.as_ul`. By default |
| 1103 |
this is ``'django/forms/errors/list/ul.html'``. This template renders |
| 1104 |
the errors in ``<li>`` tags with a wrapping ``<ul>`` with the CSS |
| 1105 |
classes as defined by :attr:`.error_class`. |
| 1106 |
|
| 1107 |
.. method:: get_context() |
| 1108 |
|
| 1109 |
Return context for rendering of errors in a template. |
| 1110 |
|
| 1111 |
The available context is: |
| 1112 |
|
| 1113 |
* ``errors`` : A list of the errors. |
| 1114 |
* ``error_class`` : A string of CSS classes. |
| 1115 |
|
| 1116 |
.. method:: render(template_name=None, context=None, renderer=None) |
| 1117 |
|
| 1118 |
The render method is called by ``__str__`` as well as by the |
| 1119 |
:meth:`.as_ul` method. |
| 1120 |
|
| 1121 |
All arguments are optional and will default to: |
| 1122 |
|
| 1123 |
* ``template_name``: Value returned by :attr:`.template_name` |
| 1124 |
* ``context``: Value returned by :meth:`.get_context` |
| 1125 |
* ``renderer``: Value returned by :attr:`.renderer` |
| 1126 |
|
| 1127 |
.. method:: as_text() |
| 1128 |
|
| 1129 |
Renders the error list using the template defined by |
| 1130 |
:attr:`.template_name_text`. |
| 1131 |
|
| 1132 |
.. method:: as_ul() |
| 1133 |
|
| 1134 |
Renders the error list using the template defined by |
| 1135 |
:attr:`.template_name_ul`. |
| 1136 |
|
| 1137 |
If you'd like to customize the rendering of errors this can be achieved by |
| 1138 |
overriding the :attr:`.template_name` attribute or more generally by |
| 1139 |
overriding the default template, see also |
| 1140 |
:ref:`overriding-built-in-form-templates`. |
| 1141 |
|
| 1142 |
More granular output |
| 1143 |
==================== |
| 1144 |
|
| 1145 |
The ``as_p()``, ``as_ul()``, and ``as_table()`` methods are shortcuts -- |
| 1146 |
they're not the only way a form object can be displayed. |
| 1147 |
|
| 1148 |
.. class:: BoundField |
| 1149 |
|
| 1150 |
Used to display HTML or access attributes for a single field of a |
| 1151 |
:class:`Form` instance. |
| 1152 |
|
| 1153 |
The ``__str__()`` method of this object displays the HTML for this field. |
| 1154 |
|
| 1155 |
You can use :attr:`.Form.bound_field_class` and |
| 1156 |
:attr:`.Field.bound_field_class` to specify a different ``BoundField`` class |
| 1157 |
per form or per field, respectively. |
| 1158 |
|
| 1159 |
See :ref:`custom-boundfield` for examples of overriding a ``BoundField``. |
| 1160 |
|
| 1161 |
To retrieve a single ``BoundField``, use dictionary lookup syntax on your form |
| 1162 |
using the field's name as the key: |
| 1163 |
|
| 1164 |
.. code-block:: pycon |
| 1165 |
|
| 1166 |
>>> form = ContactForm() |
| 1167 |
>>> print(form["subject"]) |
| 1168 |
<input id="id_subject" type="text" name="subject" maxlength="100" required> |
| 1169 |
|
| 1170 |
To retrieve all ``BoundField`` objects, iterate the form: |
| 1171 |
|
| 1172 |
.. code-block:: pycon |
| 1173 |
|
| 1174 |
>>> form = ContactForm() |
| 1175 |
>>> for boundfield in form: |
| 1176 |
... print(boundfield) |
| 1177 |
... |
| 1178 |
<input id="id_subject" type="text" name="subject" maxlength="100" required> |
| 1179 |
<input type="text" name="message" id="id_message" required> |
| 1180 |
<input type="email" name="sender" id="id_sender" required> |
| 1181 |
<input type="checkbox" name="cc_myself" id="id_cc_myself"> |
| 1182 |
|
| 1183 |
The field-specific output honors the form object's ``auto_id`` setting: |
| 1184 |
|
| 1185 |
.. code-block:: pycon |
| 1186 |
|
| 1187 |
>>> f = ContactForm(auto_id=False) |
| 1188 |
>>> print(f["message"]) |
| 1189 |
<input type="text" name="message" required> |
| 1190 |
>>> f = ContactForm(auto_id="id_%s") |
| 1191 |
>>> print(f["message"]) |
| 1192 |
<input type="text" name="message" id="id_message" required> |
| 1193 |
|
| 1194 |
Attributes of ``BoundField`` |
| 1195 |
---------------------------- |
| 1196 |
|
| 1197 |
.. attribute:: BoundField.aria_describedby |
| 1198 |
|
| 1199 |
.. versionadded:: 5.2 |
| 1200 |
|
| 1201 |
Returns an ``aria-describedby`` reference to associate a field with its |
| 1202 |
help text and errors. Returns ``None`` if ``aria-describedby`` is set in |
| 1203 |
:attr:`Widget.attrs` to preserve the user defined attribute when rendering |
| 1204 |
the form. |
| 1205 |
|
| 1206 |
.. attribute:: BoundField.auto_id |
| 1207 |
|
| 1208 |
The HTML ID attribute for this ``BoundField``. Returns an empty string |
| 1209 |
if :attr:`Form.auto_id` is ``False``. |
| 1210 |
|
| 1211 |
.. attribute:: BoundField.data |
| 1212 |
|
| 1213 |
This property returns the data for this :class:`~django.forms.BoundField` |
| 1214 |
extracted by the widget's :meth:`~django.forms.Widget.value_from_datadict` |
| 1215 |
method, or ``None`` if it wasn't given: |
| 1216 |
|
| 1217 |
.. code-block:: pycon |
| 1218 |
|
| 1219 |
>>> unbound_form = ContactForm() |
| 1220 |
>>> print(unbound_form["subject"].data) |
| 1221 |
None |
| 1222 |
>>> bound_form = ContactForm(data={"subject": "My Subject"}) |
| 1223 |
>>> print(bound_form["subject"].data) |
| 1224 |
My Subject |
| 1225 |
|
| 1226 |
.. attribute:: BoundField.errors |
| 1227 |
|
| 1228 |
A :ref:`list-like object <ref-forms-error-list-format>` that is displayed |
| 1229 |
as an HTML ``<ul class="errorlist">`` when printed: |
| 1230 |
|
| 1231 |
.. code-block:: pycon |
| 1232 |
|
| 1233 |
>>> data = {"subject": "hi", "message": "", "sender": "", "cc_myself": ""} |
| 1234 |
>>> f = ContactForm(data, auto_id=False) |
| 1235 |
>>> print(f["message"]) |
| 1236 |
<input type="text" name="message" required aria-invalid="true"> |
| 1237 |
>>> f["message"].errors |
| 1238 |
['This field is required.'] |
| 1239 |
>>> print(f["message"].errors) |
| 1240 |
<ul class="errorlist"><li>This field is required.</li></ul> |
| 1241 |
>>> f["subject"].errors |
| 1242 |
[] |
| 1243 |
>>> print(f["subject"].errors) |
| 1244 |
|
| 1245 |
>>> str(f["subject"].errors) |
| 1246 |
'' |
| 1247 |
|
| 1248 |
When rendering a field with errors, ``aria-invalid="true"`` will be set on |
| 1249 |
the field's widget to indicate there is an error to screen reader users. |
| 1250 |
|
| 1251 |
.. attribute:: BoundField.field |
| 1252 |
|
| 1253 |
The form :class:`~django.forms.Field` instance from the form class that |
| 1254 |
this :class:`~django.forms.BoundField` wraps. |
| 1255 |
|
| 1256 |
.. attribute:: BoundField.form |
| 1257 |
|
| 1258 |
The :class:`~django.forms.Form` instance this :class:`~django.forms.BoundField` |
| 1259 |
is bound to. |
| 1260 |
|
| 1261 |
.. attribute:: BoundField.help_text |
| 1262 |
|
| 1263 |
The :attr:`~django.forms.Field.help_text` of the field. |
| 1264 |
|
| 1265 |
.. attribute:: BoundField.html_name |
| 1266 |
|
| 1267 |
The name that will be used in the widget's HTML ``name`` attribute. It takes |
| 1268 |
the form :attr:`~django.forms.Form.prefix` into account. |
| 1269 |
|
| 1270 |
.. attribute:: BoundField.id_for_label |
| 1271 |
|
| 1272 |
Use this property to render the ID of this field. For example, if you are |
| 1273 |
manually constructing a ``<label>`` in your template (despite the fact that |
| 1274 |
:meth:`~BoundField.label_tag`/:meth:`~BoundField.legend_tag` will do this |
| 1275 |
for you): |
| 1276 |
|
| 1277 |
.. code-block:: html+django |
| 1278 |
|
| 1279 |
<label for="{{ form.my_field.id_for_label }}">...</label>{{ my_field }} |
| 1280 |
|
| 1281 |
By default, this will be the field's name prefixed by ``id_`` |
| 1282 |
("``id_my_field``" for the example above). You may modify the ID by setting |
| 1283 |
:attr:`~django.forms.Widget.attrs` on the field's widget. For example, |
| 1284 |
declaring a field like this:: |
| 1285 |
|
| 1286 |
my_field = forms.CharField(widget=forms.TextInput(attrs={"id": "myFIELD"})) |
| 1287 |
|
| 1288 |
and using the template above, would render something like: |
| 1289 |
|
| 1290 |
.. code-block:: html |
| 1291 |
|
| 1292 |
<label for="myFIELD">...</label><input id="myFIELD" type="text" name="my_field" required> |
| 1293 |
|
| 1294 |
.. attribute:: BoundField.initial |
| 1295 |
|
| 1296 |
Use :attr:`BoundField.initial` to retrieve initial data for a form field. |
| 1297 |
It retrieves the data from :attr:`Form.initial` if present, otherwise |
| 1298 |
trying :attr:`Field.initial`. Callable values are evaluated. See |
| 1299 |
:ref:`ref-forms-initial-form-values` for more examples. |
| 1300 |
|
| 1301 |
:attr:`BoundField.initial` caches its return value, which is useful |
| 1302 |
especially when dealing with callables whose return values can change (e.g. |
| 1303 |
``datetime.now`` or ``uuid.uuid4``): |
| 1304 |
|
| 1305 |
.. code-block:: pycon |
| 1306 |
|
| 1307 |
>>> from datetime import datetime |
| 1308 |
>>> class DatedCommentForm(CommentForm): |
| 1309 |
... created = forms.DateTimeField(initial=datetime.now) |
| 1310 |
... |
| 1311 |
>>> f = DatedCommentForm() |
| 1312 |
>>> f["created"].initial |
| 1313 |
datetime.datetime(2021, 7, 27, 9, 5, 54) |
| 1314 |
>>> f["created"].initial |
| 1315 |
datetime.datetime(2021, 7, 27, 9, 5, 54) |
| 1316 |
|
| 1317 |
Using :attr:`BoundField.initial` is recommended over |
| 1318 |
:meth:`~Form.get_initial_for_field()`. |
| 1319 |
|
| 1320 |
.. attribute:: BoundField.is_hidden |
| 1321 |
|
| 1322 |
Returns ``True`` if this :class:`~django.forms.BoundField`'s widget is |
| 1323 |
hidden. |
| 1324 |
|
| 1325 |
.. attribute:: BoundField.label |
| 1326 |
|
| 1327 |
The :attr:`~django.forms.Field.label` of the field. This is used in |
| 1328 |
:meth:`~BoundField.label_tag`/:meth:`~BoundField.legend_tag`. |
| 1329 |
|
| 1330 |
.. attribute:: BoundField.name |
| 1331 |
|
| 1332 |
The name of this field in the form: |
| 1333 |
|
| 1334 |
.. code-block:: pycon |
| 1335 |
|
| 1336 |
>>> f = ContactForm() |
| 1337 |
>>> print(f["subject"].name) |
| 1338 |
subject |
| 1339 |
>>> print(f["message"].name) |
| 1340 |
message |
| 1341 |
|
| 1342 |
.. attribute:: BoundField.template_name |
| 1343 |
|
| 1344 |
The name of the template rendered with :meth:`.BoundField.as_field_group`. |
| 1345 |
|
| 1346 |
A property returning the value of the |
| 1347 |
:attr:`~django.forms.Field.template_name` if set otherwise |
| 1348 |
:attr:`~django.forms.renderers.BaseRenderer.field_template_name`. |
| 1349 |
|
| 1350 |
.. attribute:: BoundField.use_fieldset |
| 1351 |
|
| 1352 |
Returns the value of this BoundField widget's ``use_fieldset`` attribute. |
| 1353 |
|
| 1354 |
.. attribute:: BoundField.widget_type |
| 1355 |
|
| 1356 |
Returns the lowercased class name of the wrapped field's widget, with any |
| 1357 |
trailing ``input`` or ``widget`` removed. This may be used when building |
| 1358 |
forms where the layout is dependent upon the widget type. For example: |
| 1359 |
|
| 1360 |
.. code-block:: html+django |
| 1361 |
|
| 1362 |
{% for field in form %} |
| 1363 |
{% if field.widget_type == 'checkbox' %} |
| 1364 |
# render one way |
| 1365 |
{% else %} |
| 1366 |
# render another way |
| 1367 |
{% endif %} |
| 1368 |
{% endfor %} |
| 1369 |
|
| 1370 |
|
| 1371 |
Methods of ``BoundField`` |
| 1372 |
------------------------- |
| 1373 |
|
| 1374 |
.. method:: BoundField.as_field_group() |
| 1375 |
|
| 1376 |
Renders the field using :meth:`.BoundField.render` with default values |
| 1377 |
which renders the ``BoundField``, including its label, help text and errors |
| 1378 |
using the template's :attr:`~django.forms.Field.template_name` if set |
| 1379 |
otherwise :attr:`~django.forms.renderers.BaseRenderer.field_template_name` |
| 1380 |
|
| 1381 |
.. method:: BoundField.as_hidden(attrs=None, **kwargs) |
| 1382 |
|
| 1383 |
Returns a string of HTML for representing this as an ``<input type="hidden">``. |
| 1384 |
|
| 1385 |
``**kwargs`` are passed to :meth:`~django.forms.BoundField.as_widget`. |
| 1386 |
|
| 1387 |
This method is primarily used internally. You should use a widget instead. |
| 1388 |
|
| 1389 |
.. method:: BoundField.as_widget(widget=None, attrs=None, only_initial=False) |
| 1390 |
|
| 1391 |
Renders the field by rendering the passed widget, adding any HTML |
| 1392 |
attributes passed as ``attrs``. If no widget is specified, then the |
| 1393 |
field's default widget will be used. |
| 1394 |
|
| 1395 |
``only_initial`` is used by Django internals and should not be set |
| 1396 |
explicitly. |
| 1397 |
|
| 1398 |
.. method:: BoundField.css_classes(extra_classes=None) |
| 1399 |
|
| 1400 |
When you use Django's rendering shortcuts, CSS classes are used to |
| 1401 |
indicate required form fields or fields that contain errors. If you're |
| 1402 |
manually rendering a form, you can access these CSS classes using the |
| 1403 |
``css_classes`` method: |
| 1404 |
|
| 1405 |
.. code-block:: pycon |
| 1406 |
|
| 1407 |
>>> f = ContactForm(data={"message": ""}) |
| 1408 |
>>> f["message"].css_classes() |
| 1409 |
'required' |
| 1410 |
|
| 1411 |
If you want to provide some additional classes in addition to the |
| 1412 |
error and required classes that may be required, you can provide |
| 1413 |
those classes as an argument: |
| 1414 |
|
| 1415 |
.. code-block:: pycon |
| 1416 |
|
| 1417 |
>>> f = ContactForm(data={"message": ""}) |
| 1418 |
>>> f["message"].css_classes("foo bar") |
| 1419 |
'foo bar required' |
| 1420 |
|
| 1421 |
.. method:: BoundField.get_context() |
| 1422 |
|
| 1423 |
Return the template context for rendering the field. The available context |
| 1424 |
is ``field`` being the instance of the bound field. |
| 1425 |
|
| 1426 |
.. method:: BoundField.label_tag(contents=None, attrs=None, label_suffix=None, tag=None) |
| 1427 |
|
| 1428 |
Renders a label tag for the form field using the template specified by |
| 1429 |
:attr:`.Form.template_name_label`. |
| 1430 |
|
| 1431 |
The available context is: |
| 1432 |
|
| 1433 |
* ``field``: This instance of the :class:`BoundField`. |
| 1434 |
* ``contents``: By default a concatenated string of |
| 1435 |
:attr:`BoundField.label` and :attr:`Form.label_suffix` (or |
| 1436 |
:attr:`Field.label_suffix`, if set). This can be overridden by the |
| 1437 |
``contents`` and ``label_suffix`` arguments. |
| 1438 |
* ``attrs``: A ``dict`` containing ``for``, |
| 1439 |
:attr:`Form.required_css_class`, and ``id``. ``id`` is generated by the |
| 1440 |
field's widget ``attrs`` or :attr:`BoundField.auto_id`. Additional |
| 1441 |
attributes can be provided by the ``attrs`` argument. |
| 1442 |
* ``use_tag``: A boolean which is ``True`` if the label has an ``id``. |
| 1443 |
If ``False`` the default template omits the ``tag``. |
| 1444 |
* ``tag``: An optional string to customize the tag, defaults to ``label``. |
| 1445 |
|
| 1446 |
.. tip:: |
| 1447 |
|
| 1448 |
In your template ``field`` is the instance of the ``BoundField``. |
| 1449 |
Therefore ``field.field`` accesses :attr:`BoundField.field` being |
| 1450 |
the field you declare, e.g. ``forms.CharField``. |
| 1451 |
|
| 1452 |
To separately render the label tag of a form field, you can call its |
| 1453 |
``label_tag()`` method: |
| 1454 |
|
| 1455 |
.. code-block:: pycon |
| 1456 |
|
| 1457 |
>>> f = ContactForm(data={"message": ""}) |
| 1458 |
>>> print(f["message"].label_tag()) |
| 1459 |
<label for="id_message">Message:</label> |
| 1460 |
|
| 1461 |
If you'd like to customize the rendering this can be achieved by overriding |
| 1462 |
the :attr:`.Form.template_name_label` attribute or more generally by |
| 1463 |
overriding the default template, see also |
| 1464 |
:ref:`overriding-built-in-form-templates`. |
| 1465 |
|
| 1466 |
.. method:: BoundField.legend_tag(contents=None, attrs=None, label_suffix=None) |
| 1467 |
|
| 1468 |
Calls :meth:`.label_tag` with ``tag='legend'`` to render the label with |
| 1469 |
``<legend>`` tags. This is useful when rendering radio and multiple |
| 1470 |
checkbox widgets where ``<legend>`` may be more appropriate than a |
| 1471 |
``<label>``. |
| 1472 |
|
| 1473 |
.. method:: BoundField.render(template_name=None, context=None, renderer=None) |
| 1474 |
|
| 1475 |
The render method is called by ``as_field_group``. All arguments are |
| 1476 |
optional and default to: |
| 1477 |
|
| 1478 |
* ``template_name``: :attr:`.BoundField.template_name` |
| 1479 |
* ``context``: Value returned by :meth:`.BoundField.get_context` |
| 1480 |
* ``renderer``: Value returned by :attr:`.Form.default_renderer` |
| 1481 |
|
| 1482 |
By passing ``template_name`` you can customize the template used for just a |
| 1483 |
single call. |
| 1484 |
|
| 1485 |
.. method:: BoundField.value() |
| 1486 |
|
| 1487 |
Use this method to render the raw value of this field as it would be rendered |
| 1488 |
by a ``Widget``: |
| 1489 |
|
| 1490 |
.. code-block:: pycon |
| 1491 |
|
| 1492 |
>>> initial = {"subject": "welcome"} |
| 1493 |
>>> unbound_form = ContactForm(initial=initial) |
| 1494 |
>>> bound_form = ContactForm(data={"subject": "hi"}, initial=initial) |
| 1495 |
>>> print(unbound_form["subject"].value()) |
| 1496 |
welcome |
| 1497 |
>>> print(bound_form["subject"].value()) |
| 1498 |
hi |
| 1499 |
|
| 1500 |
.. _custom-boundfield: |
| 1501 |
|
| 1502 |
Customizing ``BoundField`` |
| 1503 |
========================== |
| 1504 |
|
| 1505 |
.. attribute:: Form.bound_field_class |
| 1506 |
|
| 1507 |
.. versionadded:: 5.2 |
| 1508 |
|
| 1509 |
Define a custom :class:`~django.forms.BoundField` class to use when rendering |
| 1510 |
the form. This takes precedence over the project-level |
| 1511 |
:attr:`.BaseRenderer.bound_field_class` (along with a custom |
| 1512 |
:setting:`FORM_RENDERER`), but can be overridden by the field-level |
| 1513 |
:attr:`.Field.bound_field_class`. |
| 1514 |
|
| 1515 |
If not defined as a class variable, ``bound_field_class`` can be set via the |
| 1516 |
``bound_field_class`` argument in the :class:`Form` or :class:`Field` |
| 1517 |
constructor. |
| 1518 |
|
| 1519 |
For compatibility reasons, a custom form field can still override |
| 1520 |
:meth:`.Field.get_bound_field()` to use a custom class, though any of the |
| 1521 |
previous options are preferred. |
| 1522 |
|
| 1523 |
You may want to use a custom :class:`.BoundField` if you need to access some |
| 1524 |
additional information about a form field in a template and using a subclass of |
| 1525 |
:class:`~django.forms.Field` isn't sufficient. |
| 1526 |
|
| 1527 |
For example, if you have a ``GPSCoordinatesField``, and want to be able to |
| 1528 |
access additional information about the coordinates in a template, this could |
| 1529 |
be implemented as follows:: |
| 1530 |
|
| 1531 |
class GPSCoordinatesBoundField(BoundField): |
| 1532 |
@property |
| 1533 |
def country(self): |
| 1534 |
""" |
| 1535 |
Return the country the coordinates lie in or None if it can't be |
| 1536 |
determined. |
| 1537 |
""" |
| 1538 |
value = self.value() |
| 1539 |
if value: |
| 1540 |
return get_country_from_coordinates(value) |
| 1541 |
else: |
| 1542 |
return None |
| 1543 |
|
| 1544 |
|
| 1545 |
class GPSCoordinatesField(Field): |
| 1546 |
bound_field_class = GPSCoordinatesBoundField |
| 1547 |
|
| 1548 |
Now you can access the country in a template with |
| 1549 |
``{{ form.coordinates.country }}``. |
| 1550 |
|
| 1551 |
You may also want to customize the default form field template rendering. For |
| 1552 |
example, you can override :meth:`.BoundField.label_tag` to add a custom class:: |
| 1553 |
|
| 1554 |
class StyledLabelBoundField(BoundField): |
| 1555 |
def label_tag(self, contents=None, attrs=None, label_suffix=None, tag=None): |
| 1556 |
attrs = attrs or {} |
| 1557 |
attrs["class"] = "wide" |
| 1558 |
return super().label_tag(contents, attrs, label_suffix, tag) |
| 1559 |
|
| 1560 |
|
| 1561 |
class UserForm(forms.Form): |
| 1562 |
bound_field_class = StyledLabelBoundField |
| 1563 |
name = CharField() |
| 1564 |
|
| 1565 |
This would update the default form rendering: |
| 1566 |
|
| 1567 |
.. code-block:: pycon |
| 1568 |
|
| 1569 |
>>> f = UserForm() |
| 1570 |
>>> print(f["name"].label_tag) |
| 1571 |
<label for="id_name" class="wide">Name:</label> |
| 1572 |
|
| 1573 |
To add a CSS class to the wrapping HTML element of all fields, a ``BoundField`` |
| 1574 |
can be overridden to return a different collection of CSS classes:: |
| 1575 |
|
| 1576 |
class WrappedBoundField(BoundField): |
| 1577 |
def css_classes(self, extra_classes=None): |
| 1578 |
parent_css_classes = super().css_classes(extra_classes) |
| 1579 |
return f"field-class {parent_css_classes}".strip() |
| 1580 |
|
| 1581 |
|
| 1582 |
class UserForm(forms.Form): |
| 1583 |
bound_field_class = WrappedBoundField |
| 1584 |
name = CharField() |
| 1585 |
|
| 1586 |
This would update the form rendering as follows: |
| 1587 |
|
| 1588 |
.. code-block:: pycon |
| 1589 |
|
| 1590 |
>>> f = UserForm() |
| 1591 |
>>> print(f) |
| 1592 |
<div class="field-class"><label for="id_name">Name:</label><input type="text" name="name" required id="id_name"></div> |
| 1593 |
|
| 1594 |
Alternatively, to override the ``BoundField`` class at the project level, |
| 1595 |
:attr:`.BaseRenderer.bound_field_class` can be defined on a custom |
| 1596 |
:setting:`FORM_RENDERER`: |
| 1597 |
|
| 1598 |
.. code-block:: python |
| 1599 |
:caption: ``mysite/renderers.py`` |
| 1600 |
|
| 1601 |
from django.forms.renderers import DjangoTemplates |
| 1602 |
|
| 1603 |
from .forms import CustomBoundField |
| 1604 |
|
| 1605 |
|
| 1606 |
class CustomRenderer(DjangoTemplates): |
| 1607 |
bound_field_class = CustomBoundField |
| 1608 |
|
| 1609 |
.. code-block:: python |
| 1610 |
:caption: ``settings.py`` |
| 1611 |
|
| 1612 |
FORM_RENDERER = "mysite.renderers.CustomRenderer" |
| 1613 |
|
| 1614 |
.. _binding-uploaded-files: |
| 1615 |
|
| 1616 |
Binding uploaded files to a form |
| 1617 |
================================ |
| 1618 |
|
| 1619 |
Dealing with forms that have ``FileField`` and ``ImageField`` fields |
| 1620 |
is a little more complicated than a normal form. |
| 1621 |
|
| 1622 |
Firstly, in order to upload files, you'll need to make sure that your |
| 1623 |
``<form>`` element correctly defines the ``enctype`` as |
| 1624 |
``"multipart/form-data"``: |
| 1625 |
|
| 1626 |
.. code-block:: html |
| 1627 |
|
| 1628 |
<form enctype="multipart/form-data" method="post" action="/foo/"> |
| 1629 |
|
| 1630 |
Secondly, when you use the form, you need to bind the file data. File |
| 1631 |
data is handled separately to normal form data, so when your form |
| 1632 |
contains a ``FileField`` and ``ImageField``, you will need to specify |
| 1633 |
a second argument when you bind your form. So if we extend our |
| 1634 |
ContactForm to include an ``ImageField`` called ``mugshot``, we |
| 1635 |
need to bind the file data containing the mugshot image: |
| 1636 |
|
| 1637 |
.. code-block:: pycon |
| 1638 |
|
| 1639 |
# Bound form with an image field |
| 1640 |
>>> from django.core.files.uploadedfile import SimpleUploadedFile |
| 1641 |
>>> data = { |
| 1642 |
... "subject": "hello", |
| 1643 |
... "message": "Hi there", |
| 1644 |
... "sender": "[email protected]", |
| 1645 |
... "cc_myself": True, |
| 1646 |
... } |
| 1647 |
>>> file_data = {"mugshot": SimpleUploadedFile("face.jpg", b"file data")} |
| 1648 |
>>> f = ContactFormWithMugshot(data, file_data) |
| 1649 |
|
| 1650 |
In practice, you will usually specify ``request.FILES`` as the source |
| 1651 |
of file data (just like you use ``request.POST`` as the source of |
| 1652 |
form data): |
| 1653 |
|
| 1654 |
.. code-block:: pycon |
| 1655 |
|
| 1656 |
# Bound form with an image field, data from the request |
| 1657 |
>>> f = ContactFormWithMugshot(request.POST, request.FILES) |
| 1658 |
|
| 1659 |
Constructing an unbound form is the same as always -- omit both form data *and* |
| 1660 |
file data: |
| 1661 |
|
| 1662 |
.. code-block:: pycon |
| 1663 |
|
| 1664 |
# Unbound form with an image field |
| 1665 |
>>> f = ContactFormWithMugshot() |
| 1666 |
|
| 1667 |
Testing for multipart forms |
| 1668 |
--------------------------- |
| 1669 |
|
| 1670 |
.. method:: Form.is_multipart() |
| 1671 |
|
| 1672 |
If you're writing reusable views or templates, you may not know ahead of time |
| 1673 |
whether your form is a multipart form or not. The ``is_multipart()`` method |
| 1674 |
tells you whether the form requires multipart encoding for submission: |
| 1675 |
|
| 1676 |
.. code-block:: pycon |
| 1677 |
|
| 1678 |
>>> f = ContactFormWithMugshot() |
| 1679 |
>>> f.is_multipart() |
| 1680 |
True |
| 1681 |
|
| 1682 |
Here's an example of how you might use this in a template: |
| 1683 |
|
| 1684 |
.. code-block:: html+django |
| 1685 |
|
| 1686 |
{% if form.is_multipart %} |
| 1687 |
<form enctype="multipart/form-data" method="post" action="/foo/"> |
| 1688 |
{% else %} |
| 1689 |
<form method="post" action="/foo/"> |
| 1690 |
{% endif %} |
| 1691 |
{{ form }} |
| 1692 |
</form> |
| 1693 |
|
| 1694 |
Subclassing forms |
| 1695 |
================= |
| 1696 |
|
| 1697 |
If you have multiple ``Form`` classes that share fields, you can use |
| 1698 |
subclassing to remove redundancy. |
| 1699 |
|
| 1700 |
When you subclass a custom ``Form`` class, the resulting subclass will |
| 1701 |
include all fields of the parent class(es), followed by the fields you define |
| 1702 |
in the subclass. |
| 1703 |
|
| 1704 |
In this example, ``ContactFormWithPriority`` contains all the fields from |
| 1705 |
``ContactForm``, plus an additional field, ``priority``. The ``ContactForm`` |
| 1706 |
fields are ordered first: |
| 1707 |
|
| 1708 |
.. code-block:: pycon |
| 1709 |
|
| 1710 |
>>> class ContactFormWithPriority(ContactForm): |
| 1711 |
... priority = forms.CharField() |
| 1712 |
... |
| 1713 |
>>> f = ContactFormWithPriority(auto_id=False) |
| 1714 |
>>> print(f) |
| 1715 |
<div>Subject:<input type="text" name="subject" maxlength="100" required></div> |
| 1716 |
<div>Message:<textarea name="message" cols="40" rows="10" required></textarea></div> |
| 1717 |
<div>Sender:<input type="email" name="sender" required></div> |
| 1718 |
<div>Cc myself:<input type="checkbox" name="cc_myself"></div> |
| 1719 |
<div>Priority:<input type="text" name="priority" required></div> |
| 1720 |
|
| 1721 |
It's possible to subclass multiple forms, treating forms as mixins. In this |
| 1722 |
example, ``BeatleForm`` subclasses both ``PersonForm`` and ``InstrumentForm`` |
| 1723 |
(in that order), and its field list includes the fields from the parent |
| 1724 |
classes: |
| 1725 |
|
| 1726 |
.. code-block:: pycon |
| 1727 |
|
| 1728 |
>>> from django import forms |
| 1729 |
>>> class PersonForm(forms.Form): |
| 1730 |
... first_name = forms.CharField() |
| 1731 |
... last_name = forms.CharField() |
| 1732 |
... |
| 1733 |
>>> class InstrumentForm(forms.Form): |
| 1734 |
... instrument = forms.CharField() |
| 1735 |
... |
| 1736 |
>>> class BeatleForm(InstrumentForm, PersonForm): |
| 1737 |
... haircut_type = forms.CharField() |
| 1738 |
... |
| 1739 |
>>> b = BeatleForm(auto_id=False) |
| 1740 |
>>> print(b) |
| 1741 |
<div>First name:<input type="text" name="first_name" required></div> |
| 1742 |
<div>Last name:<input type="text" name="last_name" required></div> |
| 1743 |
<div>Instrument:<input type="text" name="instrument" required></div> |
| 1744 |
<div>Haircut type:<input type="text" name="haircut_type" required></div> |
| 1745 |
|
| 1746 |
It's possible to declaratively remove a ``Field`` inherited from a parent class |
| 1747 |
by setting the name of the field to ``None`` on the subclass. For example: |
| 1748 |
|
| 1749 |
.. code-block:: pycon |
| 1750 |
|
| 1751 |
>>> from django import forms |
| 1752 |
|
| 1753 |
>>> class ParentForm(forms.Form): |
| 1754 |
... name = forms.CharField() |
| 1755 |
... age = forms.IntegerField() |
| 1756 |
... |
| 1757 |
|
| 1758 |
>>> class ChildForm(ParentForm): |
| 1759 |
... name = None |
| 1760 |
... |
| 1761 |
|
| 1762 |
>>> list(ChildForm().fields) |
| 1763 |
['age'] |
| 1764 |
|
| 1765 |
.. _form-prefix: |
| 1766 |
|
| 1767 |
Prefixes for forms |
| 1768 |
================== |
| 1769 |
|
| 1770 |
.. attribute:: Form.prefix |
| 1771 |
|
| 1772 |
You can put several Django forms inside one ``<form>`` tag. To give each |
| 1773 |
``Form`` its own namespace, use the ``prefix`` keyword argument: |
| 1774 |
|
| 1775 |
.. code-block:: pycon |
| 1776 |
|
| 1777 |
>>> mother = PersonForm(prefix="mother") |
| 1778 |
>>> father = PersonForm(prefix="father") |
| 1779 |
>>> print(mother) |
| 1780 |
<div><label for="id_mother-first_name">First name:</label><input type="text" name="mother-first_name" required id="id_mother-first_name"></div> |
| 1781 |
<div><label for="id_mother-last_name">Last name:</label><input type="text" name="mother-last_name" required id="id_mother-last_name"></div> |
| 1782 |
>>> print(father) |
| 1783 |
<div><label for="id_father-first_name">First name:</label><input type="text" name="father-first_name" required id="id_father-first_name"></div> |
| 1784 |
<div><label for="id_father-last_name">Last name:</label><input type="text" name="father-last_name" required id="id_father-last_name"></div> |
| 1785 |
|
| 1786 |
The prefix can also be specified on the form class: |
| 1787 |
|
| 1788 |
.. code-block:: pycon |
| 1789 |
|
| 1790 |
>>> class PersonForm(forms.Form): |
| 1791 |
... ... |
| 1792 |
... prefix = "person" |
| 1793 |
... |