| 1 |
=========== |
| 2 |
Form fields |
| 3 |
=========== |
| 4 |
|
| 5 |
.. module:: django.forms.fields |
| 6 |
:synopsis: Django's built-in form fields. |
| 7 |
|
| 8 |
.. currentmodule:: django.forms |
| 9 |
|
| 10 |
.. class:: Field |
| 11 |
|
| 12 |
When you create a ``Form`` class, the most important part is defining the |
| 13 |
fields of the form. Each field has custom validation logic, along with a few |
| 14 |
other hooks. |
| 15 |
|
| 16 |
.. method:: Field.clean(value) |
| 17 |
|
| 18 |
Although the primary way you'll use ``Field`` classes is in ``Form`` classes, |
| 19 |
you can also instantiate them and use them directly to get a better idea of |
| 20 |
how they work. Each ``Field`` instance has a ``clean()`` method, which takes |
| 21 |
a single argument and either raises a |
| 22 |
``django.core.exceptions.ValidationError`` exception or returns the clean |
| 23 |
value: |
| 24 |
|
| 25 |
.. code-block:: pycon |
| 26 |
|
| 27 |
>>> from django import forms |
| 28 |
>>> f = forms.EmailField() |
| 29 |
>>> f.clean("[email protected]") |
| 30 |
'[email protected]' |
| 31 |
>>> f.clean("invalid email address") |
| 32 |
Traceback (most recent call last): |
| 33 |
... |
| 34 |
ValidationError: ['Enter a valid email address.'] |
| 35 |
|
| 36 |
.. _core-field-arguments: |
| 37 |
|
| 38 |
Core field arguments |
| 39 |
==================== |
| 40 |
|
| 41 |
Each ``Field`` class constructor takes at least these arguments. Some |
| 42 |
``Field`` classes take additional, field-specific arguments, but the following |
| 43 |
should *always* be accepted: |
| 44 |
|
| 45 |
``required`` |
| 46 |
------------ |
| 47 |
|
| 48 |
.. attribute:: Field.required |
| 49 |
|
| 50 |
By default, each ``Field`` class assumes the value is required, so if you pass |
| 51 |
an empty value -- either ``None`` or the empty string (``""``) -- then |
| 52 |
``clean()`` will raise a ``ValidationError`` exception: |
| 53 |
|
| 54 |
.. code-block:: pycon |
| 55 |
|
| 56 |
>>> from django import forms |
| 57 |
>>> f = forms.CharField() |
| 58 |
>>> f.clean("foo") |
| 59 |
'foo' |
| 60 |
>>> f.clean("") |
| 61 |
Traceback (most recent call last): |
| 62 |
... |
| 63 |
ValidationError: ['This field is required.'] |
| 64 |
>>> f.clean(None) |
| 65 |
Traceback (most recent call last): |
| 66 |
... |
| 67 |
ValidationError: ['This field is required.'] |
| 68 |
>>> f.clean(0) |
| 69 |
'0' |
| 70 |
>>> f.clean(True) |
| 71 |
'True' |
| 72 |
>>> f.clean(False) |
| 73 |
'False' |
| 74 |
|
| 75 |
To specify that a field is *not* required, pass ``required=False`` to the |
| 76 |
``Field`` constructor: |
| 77 |
|
| 78 |
.. code-block:: pycon |
| 79 |
|
| 80 |
>>> f = forms.CharField(required=False) |
| 81 |
>>> f.clean("foo") |
| 82 |
'foo' |
| 83 |
>>> f.clean("") |
| 84 |
'' |
| 85 |
>>> f.clean(None) |
| 86 |
'' |
| 87 |
>>> f.clean(0) |
| 88 |
'0' |
| 89 |
>>> f.clean(True) |
| 90 |
'True' |
| 91 |
>>> f.clean(False) |
| 92 |
'False' |
| 93 |
|
| 94 |
If a ``Field`` has ``required=False`` and you pass ``clean()`` an empty value, |
| 95 |
then ``clean()`` will return a *normalized* empty value rather than raising |
| 96 |
``ValidationError``. For ``CharField``, this will return |
| 97 |
:attr:`~CharField.empty_value` which defaults to an empty string. For other |
| 98 |
``Field`` classes, it might be ``None``. (This varies from field to field.) |
| 99 |
|
| 100 |
Widgets of required form fields have the ``required`` HTML attribute. Set the |
| 101 |
:attr:`Form.use_required_attribute` attribute to ``False`` to disable it. The |
| 102 |
``required`` attribute isn't included on forms of formsets because the browser |
| 103 |
validation may not be correct when adding and deleting formsets. |
| 104 |
|
| 105 |
``label`` |
| 106 |
--------- |
| 107 |
|
| 108 |
.. attribute:: Field.label |
| 109 |
|
| 110 |
The ``label`` argument lets you specify the "human-friendly" label for this |
| 111 |
field. This is used when the ``Field`` is displayed in a ``Form``. |
| 112 |
|
| 113 |
As explained in :ref:`ref-forms-api-outputting-html`, the default label for a |
| 114 |
``Field`` is generated from the field name by converting all underscores to |
| 115 |
spaces and upper-casing the first letter. Specify ``label`` if that default |
| 116 |
behavior doesn't result in an adequate label. |
| 117 |
|
| 118 |
Here's a full example ``Form`` that implements ``label`` for two of its fields. |
| 119 |
We've specified ``auto_id=False`` to simplify the output: |
| 120 |
|
| 121 |
.. code-block:: pycon |
| 122 |
|
| 123 |
>>> from django import forms |
| 124 |
>>> class CommentForm(forms.Form): |
| 125 |
... name = forms.CharField(label="Your name") |
| 126 |
... url = forms.URLField(label="Your website", required=False) |
| 127 |
... comment = forms.CharField() |
| 128 |
... |
| 129 |
>>> f = CommentForm(auto_id=False) |
| 130 |
>>> print(f) |
| 131 |
<div>Your name:<input type="text" name="name" required></div> |
| 132 |
<div>Your website:<input type="url" name="url"></div> |
| 133 |
<div>Comment:<input type="text" name="comment" required></div> |
| 134 |
|
| 135 |
``label_suffix`` |
| 136 |
---------------- |
| 137 |
|
| 138 |
.. attribute:: Field.label_suffix |
| 139 |
|
| 140 |
The ``label_suffix`` argument lets you override the form's |
| 141 |
:attr:`~django.forms.Form.label_suffix` on a per-field basis: |
| 142 |
|
| 143 |
.. code-block:: pycon |
| 144 |
|
| 145 |
>>> class ContactForm(forms.Form): |
| 146 |
... age = forms.IntegerField() |
| 147 |
... nationality = forms.CharField() |
| 148 |
... captcha_answer = forms.IntegerField(label="2 + 2", label_suffix=" =") |
| 149 |
... |
| 150 |
>>> f = ContactForm(label_suffix="?") |
| 151 |
>>> print(f) |
| 152 |
<div><label for="id_age">Age?</label><input type="number" name="age" required id="id_age"></div> |
| 153 |
<div><label for="id_nationality">Nationality?</label><input type="text" name="nationality" required id="id_nationality"></div> |
| 154 |
<div><label for="id_captcha_answer">2 + 2 =</label><input type="number" name="captcha_answer" required id="id_captcha_answer"></div> |
| 155 |
|
| 156 |
``initial`` |
| 157 |
----------- |
| 158 |
|
| 159 |
.. attribute:: Field.initial |
| 160 |
|
| 161 |
The ``initial`` argument lets you specify the initial value to use when |
| 162 |
rendering this ``Field`` in an unbound ``Form``. |
| 163 |
|
| 164 |
To specify dynamic initial data, see the :attr:`Form.initial` parameter. |
| 165 |
|
| 166 |
The use-case for this is when you want to display an "empty" form in which a |
| 167 |
field is initialized to a particular value. For example: |
| 168 |
|
| 169 |
.. code-block:: pycon |
| 170 |
|
| 171 |
>>> from django import forms |
| 172 |
>>> class CommentForm(forms.Form): |
| 173 |
... name = forms.CharField(initial="Your name") |
| 174 |
... url = forms.URLField(initial="https://") |
| 175 |
... comment = forms.CharField() |
| 176 |
... |
| 177 |
>>> f = CommentForm(auto_id=False) |
| 178 |
>>> print(f) |
| 179 |
<div>Name:<input type="text" name="name" value="Your name" required></div> |
| 180 |
<div>Url:<input type="url" name="url" value="https://" required></div> |
| 181 |
<div>Comment:<input type="text" name="comment" required></div> |
| 182 |
|
| 183 |
You may be thinking, why not just pass a dictionary of the initial values as |
| 184 |
data when displaying the form? Well, if you do that, you'll trigger validation, |
| 185 |
and the HTML output will include any validation errors: |
| 186 |
|
| 187 |
.. code-block:: pycon |
| 188 |
|
| 189 |
>>> class CommentForm(forms.Form): |
| 190 |
... name = forms.CharField() |
| 191 |
... url = forms.URLField() |
| 192 |
... comment = forms.CharField() |
| 193 |
... |
| 194 |
>>> default_data = {"name": "Your name", "url": "https://"} |
| 195 |
>>> f = CommentForm(default_data, auto_id=False) |
| 196 |
>>> print(f) |
| 197 |
<div>Name: |
| 198 |
<input type="text" name="name" value="Your name" required> |
| 199 |
</div> |
| 200 |
<div>Url: |
| 201 |
<ul class="errorlist"><li>Enter a valid URL.</li></ul> |
| 202 |
<input type="url" name="url" value="https://" required aria-invalid="true"> |
| 203 |
</div> |
| 204 |
<div>Comment: |
| 205 |
<ul class="errorlist"><li>This field is required.</li></ul> |
| 206 |
<input type="text" name="comment" required aria-invalid="true"> |
| 207 |
</div> |
| 208 |
|
| 209 |
This is why ``initial`` values are only displayed for unbound forms. For bound |
| 210 |
forms, the HTML output will use the bound data. |
| 211 |
|
| 212 |
Also note that ``initial`` values are *not* used as "fallback" data in |
| 213 |
validation if a particular field's value is not given. ``initial`` values are |
| 214 |
*only* intended for initial form display: |
| 215 |
|
| 216 |
.. code-block:: pycon |
| 217 |
|
| 218 |
>>> class CommentForm(forms.Form): |
| 219 |
... name = forms.CharField(initial="Your name") |
| 220 |
... url = forms.URLField(initial="https://") |
| 221 |
... comment = forms.CharField() |
| 222 |
... |
| 223 |
>>> data = {"name": "", "url": "", "comment": "Foo"} |
| 224 |
>>> f = CommentForm(data) |
| 225 |
>>> f.is_valid() |
| 226 |
False |
| 227 |
# The form does *not* fallback to using the initial values. |
| 228 |
>>> f.errors |
| 229 |
{'url': ['This field is required.'], 'name': ['This field is required.']} |
| 230 |
|
| 231 |
Instead of a constant, you can also pass any callable: |
| 232 |
|
| 233 |
.. code-block:: pycon |
| 234 |
|
| 235 |
>>> import datetime |
| 236 |
>>> class DateForm(forms.Form): |
| 237 |
... day = forms.DateField(initial=datetime.date.today) |
| 238 |
... |
| 239 |
>>> print(DateForm()) |
| 240 |
<div><label for="id_day">Day:</label><input type="text" name="day" value="2023-02-11" required id="id_day"></div> |
| 241 |
|
| 242 |
The callable will be evaluated only when the unbound form is displayed, not when it is defined. |
| 243 |
|
| 244 |
``widget`` |
| 245 |
---------- |
| 246 |
|
| 247 |
.. attribute:: Field.widget |
| 248 |
|
| 249 |
The ``widget`` argument lets you specify a ``Widget`` class to use when |
| 250 |
rendering this ``Field``. See :doc:`/ref/forms/widgets` for more information. |
| 251 |
|
| 252 |
``help_text`` |
| 253 |
------------- |
| 254 |
|
| 255 |
.. attribute:: Field.help_text |
| 256 |
|
| 257 |
The ``help_text`` argument lets you specify descriptive text for this |
| 258 |
``Field``. If you provide ``help_text``, it will be displayed next to the |
| 259 |
``Field`` when the ``Field`` is rendered by one of the convenience ``Form`` |
| 260 |
methods (e.g., ``as_ul()``). |
| 261 |
|
| 262 |
Like the model field's :attr:`~django.db.models.Field.help_text`, this value |
| 263 |
isn't HTML-escaped in automatically-generated forms. |
| 264 |
|
| 265 |
Here's a full example ``Form`` that implements ``help_text`` for two of its |
| 266 |
fields. We've specified ``auto_id=False`` to simplify the output: |
| 267 |
|
| 268 |
.. code-block:: pycon |
| 269 |
|
| 270 |
>>> from django import forms |
| 271 |
>>> class HelpTextContactForm(forms.Form): |
| 272 |
... subject = forms.CharField(max_length=100, help_text="100 characters max.") |
| 273 |
... message = forms.CharField() |
| 274 |
... sender = forms.EmailField(help_text="A valid email address, please.") |
| 275 |
... cc_myself = forms.BooleanField(required=False) |
| 276 |
... |
| 277 |
>>> f = HelpTextContactForm(auto_id=False) |
| 278 |
>>> print(f) |
| 279 |
<div>Subject:<div class="helptext">100 characters max.</div><input type="text" name="subject" maxlength="100" required></div> |
| 280 |
<div>Message:<input type="text" name="message" required></div> |
| 281 |
<div>Sender:<div class="helptext">A valid email address, please.</div><input type="email" name="sender" required></div> |
| 282 |
<div>Cc myself:<input type="checkbox" name="cc_myself"></div> |
| 283 |
|
| 284 |
When a field has help text it is associated with its input using the |
| 285 |
``aria-describedby`` HTML attribute. If the widget is rendered in a |
| 286 |
``<fieldset>`` then ``aria-describedby`` is added to this element, otherwise it |
| 287 |
is added to the widget's ``<input>``: |
| 288 |
|
| 289 |
.. code-block:: pycon |
| 290 |
|
| 291 |
>>> from django import forms |
| 292 |
>>> class UserForm(forms.Form): |
| 293 |
... username = forms.CharField(max_length=255, help_text="e.g., [email protected]") |
| 294 |
... |
| 295 |
>>> f = UserForm() |
| 296 |
>>> print(f) |
| 297 |
<div> |
| 298 |
<label for="id_username">Username:</label> |
| 299 |
<div class="helptext" id="id_username_helptext">e.g., [email protected]</div> |
| 300 |
<input type="text" name="username" maxlength="255" required aria-describedby="id_username_helptext" id="id_username"> |
| 301 |
</div> |
| 302 |
|
| 303 |
When adding a custom ``aria-describedby`` attribute, make sure to also include |
| 304 |
the ``id`` of the ``help_text`` element (if used) in the desired order. For |
| 305 |
screen reader users, descriptions will be read in their order of appearance |
| 306 |
inside ``aria-describedby``: |
| 307 |
|
| 308 |
.. code-block:: pycon |
| 309 |
|
| 310 |
>>> class UserForm(forms.Form): |
| 311 |
... username = forms.CharField( |
| 312 |
... max_length=255, |
| 313 |
... help_text="e.g., [email protected]", |
| 314 |
... widget=forms.TextInput( |
| 315 |
... attrs={"aria-describedby": "custom-description id_username_helptext"}, |
| 316 |
... ), |
| 317 |
... ) |
| 318 |
... |
| 319 |
>>> f = UserForm() |
| 320 |
>>> print(f["username"]) |
| 321 |
<input type="text" name="username" aria-describedby="custom-description id_username_helptext" maxlength="255" id="id_username" required> |
| 322 |
|
| 323 |
.. versionchanged:: 5.1 |
| 324 |
|
| 325 |
``aria-describedby`` support was added for ``<fieldset>``. |
| 326 |
|
| 327 |
``error_messages`` |
| 328 |
------------------ |
| 329 |
|
| 330 |
.. attribute:: Field.error_messages |
| 331 |
|
| 332 |
The ``error_messages`` argument lets you override the default messages that the |
| 333 |
field will raise. Pass in a dictionary with keys matching the error messages you |
| 334 |
want to override. For example, here is the default error message: |
| 335 |
|
| 336 |
.. code-block:: pycon |
| 337 |
|
| 338 |
>>> from django import forms |
| 339 |
>>> generic = forms.CharField() |
| 340 |
>>> generic.clean("") |
| 341 |
Traceback (most recent call last): |
| 342 |
... |
| 343 |
ValidationError: ['This field is required.'] |
| 344 |
|
| 345 |
And here is a custom error message: |
| 346 |
|
| 347 |
.. code-block:: pycon |
| 348 |
|
| 349 |
>>> name = forms.CharField(error_messages={"required": "Please enter your name"}) |
| 350 |
>>> name.clean("") |
| 351 |
Traceback (most recent call last): |
| 352 |
... |
| 353 |
ValidationError: ['Please enter your name'] |
| 354 |
|
| 355 |
In the `built-in Field classes`_ section below, each ``Field`` defines the |
| 356 |
error message keys it uses. |
| 357 |
|
| 358 |
``validators`` |
| 359 |
-------------- |
| 360 |
|
| 361 |
.. attribute:: Field.validators |
| 362 |
|
| 363 |
The ``validators`` argument lets you provide a list of validation functions |
| 364 |
for this field. |
| 365 |
|
| 366 |
See the :doc:`validators documentation </ref/validators>` for more information. |
| 367 |
|
| 368 |
``localize`` |
| 369 |
------------ |
| 370 |
|
| 371 |
.. attribute:: Field.localize |
| 372 |
|
| 373 |
The ``localize`` argument enables the localization of form data input, as well |
| 374 |
as the rendered output. |
| 375 |
|
| 376 |
See the :doc:`format localization documentation </topics/i18n/formatting>` for |
| 377 |
more information. |
| 378 |
|
| 379 |
``disabled`` |
| 380 |
------------ |
| 381 |
|
| 382 |
.. attribute:: Field.disabled |
| 383 |
|
| 384 |
The ``disabled`` boolean argument, when set to ``True``, disables a form field |
| 385 |
using the ``disabled`` HTML attribute so that it won't be editable by users. |
| 386 |
Even if a user tampers with the field's value submitted to the server, it will |
| 387 |
be ignored in favor of the value from the form's initial data. |
| 388 |
|
| 389 |
``template_name`` |
| 390 |
----------------- |
| 391 |
|
| 392 |
.. attribute:: Field.template_name |
| 393 |
|
| 394 |
The ``template_name`` argument allows a custom template to be used when the |
| 395 |
field is rendered with :meth:`~django.forms.BoundField.as_field_group`. By |
| 396 |
default this value is set to ``"django/forms/field.html"``. Can be changed per |
| 397 |
field by overriding this attribute or more generally by overriding the default |
| 398 |
template, see also :ref:`overriding-built-in-field-templates`. |
| 399 |
|
| 400 |
``bound_field_class`` |
| 401 |
--------------------- |
| 402 |
|
| 403 |
.. attribute:: Field.bound_field_class |
| 404 |
|
| 405 |
.. versionadded:: 5.2 |
| 406 |
|
| 407 |
The ``bound_field_class`` attribute allows a per-field override of |
| 408 |
:attr:`.Form.bound_field_class`. |
| 409 |
|
| 410 |
Checking if the field data has changed |
| 411 |
====================================== |
| 412 |
|
| 413 |
``has_changed()`` |
| 414 |
----------------- |
| 415 |
|
| 416 |
.. method:: Field.has_changed() |
| 417 |
|
| 418 |
The ``has_changed()`` method is used to determine if the field value has changed |
| 419 |
from the initial value. Returns ``True`` or ``False``. |
| 420 |
|
| 421 |
See the :class:`Form.has_changed()` documentation for more information. |
| 422 |
|
| 423 |
.. _built-in-fields: |
| 424 |
|
| 425 |
Built-in ``Field`` classes |
| 426 |
========================== |
| 427 |
|
| 428 |
Naturally, the ``forms`` library comes with a set of ``Field`` classes that |
| 429 |
represent common validation needs. This section documents each built-in field. |
| 430 |
|
| 431 |
For each field, we describe the default widget used if you don't specify |
| 432 |
``widget``. We also specify the value returned when you provide an empty value |
| 433 |
(see the section on ``required`` above to understand what that means). |
| 434 |
|
| 435 |
``BooleanField`` |
| 436 |
---------------- |
| 437 |
|
| 438 |
.. class:: BooleanField(**kwargs) |
| 439 |
|
| 440 |
* Default widget: :class:`CheckboxInput` |
| 441 |
* Empty value: ``False`` |
| 442 |
* Normalizes to: A Python ``True`` or ``False`` value. |
| 443 |
* Validates that the value is ``True`` (e.g. the check box is checked) if |
| 444 |
the field has ``required=True``. |
| 445 |
* Error message keys: ``required`` |
| 446 |
|
| 447 |
.. note:: |
| 448 |
|
| 449 |
Since all ``Field`` subclasses have ``required=True`` by default, the |
| 450 |
validation condition here is important. If you want to include a boolean |
| 451 |
in your form that can be either ``True`` or ``False`` (e.g. a checked or |
| 452 |
unchecked checkbox), you must remember to pass in ``required=False`` when |
| 453 |
creating the ``BooleanField``. |
| 454 |
|
| 455 |
``CharField`` |
| 456 |
------------- |
| 457 |
|
| 458 |
.. class:: CharField(**kwargs) |
| 459 |
|
| 460 |
* Default widget: :class:`TextInput` |
| 461 |
* Empty value: Whatever you've given as :attr:`empty_value`. |
| 462 |
* Normalizes to: A string. |
| 463 |
* Uses :class:`~django.core.validators.MaxLengthValidator` and |
| 464 |
:class:`~django.core.validators.MinLengthValidator` if ``max_length`` and |
| 465 |
``min_length`` are provided. Otherwise, all inputs are valid. |
| 466 |
* Error message keys: ``required``, ``max_length``, ``min_length`` |
| 467 |
|
| 468 |
Has the following optional arguments for validation: |
| 469 |
|
| 470 |
.. attribute:: max_length |
| 471 |
.. attribute:: min_length |
| 472 |
|
| 473 |
If provided, these arguments ensure that the string is at most or at |
| 474 |
least the given length. |
| 475 |
|
| 476 |
.. attribute:: strip |
| 477 |
|
| 478 |
If ``True`` (default), the value will be stripped of leading and |
| 479 |
trailing whitespace. |
| 480 |
|
| 481 |
.. attribute:: empty_value |
| 482 |
|
| 483 |
The value to use to represent "empty". Defaults to an empty string. |
| 484 |
|
| 485 |
``ChoiceField`` |
| 486 |
--------------- |
| 487 |
|
| 488 |
.. class:: ChoiceField(**kwargs) |
| 489 |
|
| 490 |
* Default widget: :class:`Select` |
| 491 |
* Empty value: ``''`` (an empty string) |
| 492 |
* Normalizes to: A string. |
| 493 |
* Validates that the given value exists in the list of choices. |
| 494 |
* Error message keys: ``required``, ``invalid_choice`` |
| 495 |
|
| 496 |
The ``invalid_choice`` error message may contain ``%(value)s``, which will be |
| 497 |
replaced with the selected choice. |
| 498 |
|
| 499 |
Takes one extra argument: |
| 500 |
|
| 501 |
.. attribute:: choices |
| 502 |
|
| 503 |
Either an :term:`iterable` of 2-tuples to use as choices for this |
| 504 |
field, :ref:`enumeration type <field-choices-enum-types>`, or a |
| 505 |
callable that returns such an iterable. This argument accepts the same |
| 506 |
formats as the ``choices`` argument to a model field. See the |
| 507 |
:ref:`model field reference documentation on choices <field-choices>` |
| 508 |
for more details. If the argument is a callable, it is evaluated each |
| 509 |
time the field's form is initialized, in addition to during rendering. |
| 510 |
Defaults to an empty list. |
| 511 |
|
| 512 |
.. admonition:: Choice type |
| 513 |
|
| 514 |
This field normalizes choices to strings, so if choices are required in |
| 515 |
other data types, such as integers or booleans, consider using |
| 516 |
:class:`TypedChoiceField` instead. |
| 517 |
|
| 518 |
``DateField`` |
| 519 |
------------- |
| 520 |
|
| 521 |
.. class:: DateField(**kwargs) |
| 522 |
|
| 523 |
* Default widget: :class:`DateInput` |
| 524 |
* Empty value: ``None`` |
| 525 |
* Normalizes to: A Python ``datetime.date`` object. |
| 526 |
* Validates that the given value is either a ``datetime.date``, |
| 527 |
``datetime.datetime`` or string formatted in a particular date format. |
| 528 |
* Error message keys: ``required``, ``invalid`` |
| 529 |
|
| 530 |
Takes one optional argument: |
| 531 |
|
| 532 |
.. attribute:: input_formats |
| 533 |
|
| 534 |
An iterable of formats used to attempt to convert a string to a valid |
| 535 |
``datetime.date`` object. |
| 536 |
|
| 537 |
If no ``input_formats`` argument is provided, the default input formats are |
| 538 |
taken from the active locale format ``DATE_INPUT_FORMATS`` key, or from |
| 539 |
:setting:`DATE_INPUT_FORMATS` if localization is disabled. See also |
| 540 |
:doc:`format localization </topics/i18n/formatting>`. |
| 541 |
|
| 542 |
``DateTimeField`` |
| 543 |
----------------- |
| 544 |
|
| 545 |
.. class:: DateTimeField(**kwargs) |
| 546 |
|
| 547 |
* Default widget: :class:`DateTimeInput` |
| 548 |
* Empty value: ``None`` |
| 549 |
* Normalizes to: A Python ``datetime.datetime`` object. |
| 550 |
* Validates that the given value is either a ``datetime.datetime``, |
| 551 |
``datetime.date`` or string formatted in a particular datetime format. |
| 552 |
* Error message keys: ``required``, ``invalid`` |
| 553 |
|
| 554 |
Takes one optional argument: |
| 555 |
|
| 556 |
.. attribute:: input_formats |
| 557 |
|
| 558 |
An iterable of formats used to attempt to convert a string to a valid |
| 559 |
``datetime.datetime`` object, in addition to ISO 8601 formats. |
| 560 |
|
| 561 |
The field always accepts strings in ISO 8601 formatted dates or similar |
| 562 |
recognized by :func:`~django.utils.dateparse.parse_datetime`. Some examples |
| 563 |
are: |
| 564 |
|
| 565 |
* ``'2006-10-25 14:30:59'`` |
| 566 |
* ``'2006-10-25T14:30:59'`` |
| 567 |
* ``'2006-10-25 14:30'`` |
| 568 |
* ``'2006-10-25T14:30'`` |
| 569 |
* ``'2006-10-25T14:30Z'`` |
| 570 |
* ``'2006-10-25T14:30+02:00'`` |
| 571 |
* ``'2006-10-25'`` |
| 572 |
|
| 573 |
If no ``input_formats`` argument is provided, the default input formats are |
| 574 |
taken from the active locale format ``DATETIME_INPUT_FORMATS`` and |
| 575 |
``DATE_INPUT_FORMATS`` keys, or from :setting:`DATETIME_INPUT_FORMATS` and |
| 576 |
:setting:`DATE_INPUT_FORMATS` if localization is disabled. See also |
| 577 |
:doc:`format localization </topics/i18n/formatting>`. |
| 578 |
|
| 579 |
``DecimalField`` |
| 580 |
---------------- |
| 581 |
|
| 582 |
.. class:: DecimalField(**kwargs) |
| 583 |
|
| 584 |
* Default widget: :class:`NumberInput` when :attr:`Field.localize` is |
| 585 |
``False``, else :class:`TextInput`. |
| 586 |
* Empty value: ``None`` |
| 587 |
* Normalizes to: A Python ``decimal``. |
| 588 |
* Validates that the given value is a decimal. Uses |
| 589 |
:class:`~django.core.validators.MaxValueValidator` and |
| 590 |
:class:`~django.core.validators.MinValueValidator` if ``max_value`` and |
| 591 |
``min_value`` are provided. Uses |
| 592 |
:class:`~django.core.validators.StepValueValidator` if ``step_size`` is |
| 593 |
provided. Leading and trailing whitespace is ignored. |
| 594 |
* Error message keys: ``required``, ``invalid``, ``max_value``, |
| 595 |
``min_value``, ``max_digits``, ``max_decimal_places``, |
| 596 |
``max_whole_digits``, ``step_size``. |
| 597 |
|
| 598 |
The ``max_value`` and ``min_value`` error messages may contain |
| 599 |
``%(limit_value)s``, which will be substituted by the appropriate limit. |
| 600 |
Similarly, the ``max_digits``, ``max_decimal_places`` and |
| 601 |
``max_whole_digits`` error messages may contain ``%(max)s``. |
| 602 |
|
| 603 |
Takes five optional arguments: |
| 604 |
|
| 605 |
.. attribute:: max_value |
| 606 |
.. attribute:: min_value |
| 607 |
|
| 608 |
These control the range of values permitted in the field, and should be |
| 609 |
given as ``decimal.Decimal`` values. |
| 610 |
|
| 611 |
.. attribute:: max_digits |
| 612 |
|
| 613 |
The maximum number of digits (those before the decimal point plus those |
| 614 |
after the decimal point, with leading zeros stripped) permitted in the |
| 615 |
value. |
| 616 |
|
| 617 |
.. attribute:: decimal_places |
| 618 |
|
| 619 |
The maximum number of decimal places permitted. |
| 620 |
|
| 621 |
.. attribute:: step_size |
| 622 |
|
| 623 |
Limit valid inputs to an integral multiple of ``step_size``. If |
| 624 |
``min_value`` is also provided, it's added as an offset to determine if |
| 625 |
the step size matches. |
| 626 |
|
| 627 |
``DurationField`` |
| 628 |
----------------- |
| 629 |
|
| 630 |
.. class:: DurationField(**kwargs) |
| 631 |
|
| 632 |
* Default widget: :class:`TextInput` |
| 633 |
* Empty value: ``None`` |
| 634 |
* Normalizes to: A Python :class:`~python:datetime.timedelta`. |
| 635 |
* Validates that the given value is a string which can be converted into a |
| 636 |
``timedelta``. The value must be between :attr:`datetime.timedelta.min` |
| 637 |
and :attr:`datetime.timedelta.max`. |
| 638 |
* Error message keys: ``required``, ``invalid``, ``overflow``. |
| 639 |
|
| 640 |
Accepts any format understood by |
| 641 |
:func:`~django.utils.dateparse.parse_duration`. |
| 642 |
|
| 643 |
``EmailField`` |
| 644 |
-------------- |
| 645 |
|
| 646 |
.. class:: EmailField(**kwargs) |
| 647 |
|
| 648 |
* Default widget: :class:`EmailInput` |
| 649 |
* Empty value: Whatever you've given as ``empty_value``. |
| 650 |
* Normalizes to: A string. |
| 651 |
* Uses :class:`~django.core.validators.EmailValidator` to validate that |
| 652 |
the given value is a valid email address, using a moderately complex |
| 653 |
regular expression. |
| 654 |
* Error message keys: ``required``, ``invalid`` |
| 655 |
|
| 656 |
Has the optional arguments ``max_length``, ``min_length``, and |
| 657 |
``empty_value`` which work just as they do for :class:`CharField`. The |
| 658 |
``max_length`` argument defaults to 320 (see :rfc:`3696#section-3`). |
| 659 |
|
| 660 |
``FileField`` |
| 661 |
------------- |
| 662 |
|
| 663 |
.. class:: FileField(**kwargs) |
| 664 |
|
| 665 |
* Default widget: :class:`ClearableFileInput` |
| 666 |
* Empty value: ``None`` |
| 667 |
* Normalizes to: An ``UploadedFile`` object that wraps the file content |
| 668 |
and file name into a single object. |
| 669 |
* Can validate that non-empty file data has been bound to the form. |
| 670 |
* Error message keys: ``required``, ``invalid``, ``missing``, ``empty``, |
| 671 |
``max_length`` |
| 672 |
|
| 673 |
Has the optional arguments for validation: ``max_length`` and |
| 674 |
``allow_empty_file``. If provided, these ensure that the file name is at |
| 675 |
most the given length, and that validation will succeed even if the file |
| 676 |
content is empty. |
| 677 |
|
| 678 |
To learn more about the ``UploadedFile`` object, see the :doc:`file uploads |
| 679 |
documentation </topics/http/file-uploads>`. |
| 680 |
|
| 681 |
When you use a ``FileField`` in a form, you must also remember to |
| 682 |
:ref:`bind the file data to the form <binding-uploaded-files>`. |
| 683 |
|
| 684 |
The ``max_length`` error refers to the length of the filename. In the error |
| 685 |
message for that key, ``%(max)d`` will be replaced with the maximum filename |
| 686 |
length and ``%(length)d`` will be replaced with the current filename length. |
| 687 |
|
| 688 |
``FilePathField`` |
| 689 |
----------------- |
| 690 |
|
| 691 |
.. class:: FilePathField(**kwargs) |
| 692 |
|
| 693 |
* Default widget: :class:`Select` |
| 694 |
* Empty value: ``''`` (an empty string) |
| 695 |
* Normalizes to: A string. |
| 696 |
* Validates that the selected choice exists in the list of choices. |
| 697 |
* Error message keys: ``required``, ``invalid_choice`` |
| 698 |
|
| 699 |
The field allows choosing from files inside a certain directory. It takes five |
| 700 |
extra arguments; only ``path`` is required: |
| 701 |
|
| 702 |
.. attribute:: path |
| 703 |
|
| 704 |
The absolute path to the directory whose contents you want listed. This |
| 705 |
directory must exist. |
| 706 |
|
| 707 |
.. attribute:: recursive |
| 708 |
|
| 709 |
If ``False`` (the default) only the direct contents of ``path`` will be |
| 710 |
offered as choices. If ``True``, the directory will be descended into |
| 711 |
recursively and all descendants will be listed as choices. |
| 712 |
|
| 713 |
.. attribute:: match |
| 714 |
|
| 715 |
A regular expression pattern; only files with names matching this expression |
| 716 |
will be allowed as choices. |
| 717 |
|
| 718 |
.. attribute:: allow_files |
| 719 |
|
| 720 |
Optional. Either ``True`` or ``False``. Default is ``True``. Specifies |
| 721 |
whether files in the specified location should be included. Either this or |
| 722 |
:attr:`allow_folders` must be ``True``. |
| 723 |
|
| 724 |
.. attribute:: allow_folders |
| 725 |
|
| 726 |
Optional. Either ``True`` or ``False``. Default is ``False``. Specifies |
| 727 |
whether folders in the specified location should be included. Either this or |
| 728 |
:attr:`allow_files` must be ``True``. |
| 729 |
|
| 730 |
|
| 731 |
``FloatField`` |
| 732 |
-------------- |
| 733 |
|
| 734 |
.. class:: FloatField(**kwargs) |
| 735 |
|
| 736 |
* Default widget: :class:`NumberInput` when :attr:`Field.localize` is |
| 737 |
``False``, else :class:`TextInput`. |
| 738 |
* Empty value: ``None`` |
| 739 |
* Normalizes to: A Python float. |
| 740 |
* Validates that the given value is a float. Uses |
| 741 |
:class:`~django.core.validators.MaxValueValidator` and |
| 742 |
:class:`~django.core.validators.MinValueValidator` if ``max_value`` and |
| 743 |
``min_value`` are provided. Uses |
| 744 |
:class:`~django.core.validators.StepValueValidator` if ``step_size`` is |
| 745 |
provided. Leading and trailing whitespace is allowed, as in Python's |
| 746 |
``float()`` function. |
| 747 |
* Error message keys: ``required``, ``invalid``, ``max_value``, |
| 748 |
``min_value``, ``step_size``. |
| 749 |
|
| 750 |
Takes three optional arguments: |
| 751 |
|
| 752 |
.. attribute:: max_value |
| 753 |
.. attribute:: min_value |
| 754 |
|
| 755 |
These control the range of values permitted in the field. |
| 756 |
|
| 757 |
.. attribute:: step_size |
| 758 |
|
| 759 |
Limit valid inputs to an integral multiple of ``step_size``. If |
| 760 |
``min_value`` is also provided, it's added as an offset to determine if |
| 761 |
the step size matches. |
| 762 |
|
| 763 |
``GenericIPAddressField`` |
| 764 |
------------------------- |
| 765 |
|
| 766 |
.. class:: GenericIPAddressField(**kwargs) |
| 767 |
|
| 768 |
A field containing either an IPv4 or an IPv6 address. |
| 769 |
|
| 770 |
* Default widget: :class:`TextInput` |
| 771 |
* Empty value: ``''`` (an empty string) |
| 772 |
* Normalizes to: A string. IPv6 addresses are normalized as described below. |
| 773 |
* Validates that the given value is a valid IP address. |
| 774 |
* Error message keys: ``required``, ``invalid``, ``max_length`` |
| 775 |
|
| 776 |
The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2, |
| 777 |
including using the IPv4 format suggested in paragraph 3 of that section, like |
| 778 |
``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to |
| 779 |
``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters |
| 780 |
are converted to lowercase. |
| 781 |
|
| 782 |
Takes three optional arguments: |
| 783 |
|
| 784 |
.. attribute:: protocol |
| 785 |
|
| 786 |
Limits valid inputs to the specified protocol. |
| 787 |
Accepted values are ``both`` (default), ``IPv4`` |
| 788 |
or ``IPv6``. Matching is case insensitive. |
| 789 |
|
| 790 |
.. attribute:: unpack_ipv4 |
| 791 |
|
| 792 |
Unpacks IPv4 mapped addresses like ``::ffff:192.0.2.1``. |
| 793 |
If this option is enabled that address would be unpacked to |
| 794 |
``192.0.2.1``. Default is disabled. Can only be used |
| 795 |
when ``protocol`` is set to ``'both'``. |
| 796 |
|
| 797 |
.. attribute:: max_length |
| 798 |
|
| 799 |
Defaults to 39, and behaves the same way as it does for |
| 800 |
:class:`CharField`. |
| 801 |
|
| 802 |
.. versionchanged:: 4.2.18 |
| 803 |
|
| 804 |
The default value for ``max_length`` was set to 39 characters. |
| 805 |
|
| 806 |
``ImageField`` |
| 807 |
-------------- |
| 808 |
|
| 809 |
.. class:: ImageField(**kwargs) |
| 810 |
|
| 811 |
* Default widget: :class:`ClearableFileInput` |
| 812 |
* Empty value: ``None`` |
| 813 |
* Normalizes to: An ``UploadedFile`` object that wraps the file content |
| 814 |
and file name into a single object. |
| 815 |
* Validates that file data has been bound to the form. Also uses |
| 816 |
:class:`~django.core.validators.FileExtensionValidator` to validate that |
| 817 |
the file extension is supported by Pillow. |
| 818 |
* Error message keys: ``required``, ``invalid``, ``missing``, ``empty``, |
| 819 |
``invalid_image`` |
| 820 |
|
| 821 |
Using an ``ImageField`` requires that :pypi:`pillow` is installed with |
| 822 |
support for the image formats you use. If you encounter a ``corrupt image`` |
| 823 |
error when you upload an image, it usually means that Pillow doesn't |
| 824 |
understand its format. To fix this, install the appropriate library and |
| 825 |
reinstall Pillow. |
| 826 |
|
| 827 |
When you use an ``ImageField`` on a form, you must also remember to |
| 828 |
:ref:`bind the file data to the form <binding-uploaded-files>`. |
| 829 |
|
| 830 |
After the field has been cleaned and validated, the ``UploadedFile`` |
| 831 |
object will have an additional ``image`` attribute containing the Pillow |
| 832 |
`Image`_ instance used to check if the file was a valid image. Pillow |
| 833 |
closes the underlying file descriptor after verifying an image, so while |
| 834 |
non-image data attributes, such as ``format``, ``height``, and ``width``, |
| 835 |
are available, methods that access the underlying image data, such as |
| 836 |
``getdata()`` or ``getpixel()``, cannot be used without reopening the file. |
| 837 |
For example: |
| 838 |
|
| 839 |
.. code-block:: pycon |
| 840 |
|
| 841 |
>>> from PIL import Image |
| 842 |
>>> from django import forms |
| 843 |
>>> from django.core.files.uploadedfile import SimpleUploadedFile |
| 844 |
>>> class ImageForm(forms.Form): |
| 845 |
... img = forms.ImageField() |
| 846 |
... |
| 847 |
>>> file_data = {"img": SimpleUploadedFile("test.png", b"file data")} |
| 848 |
>>> form = ImageForm({}, file_data) |
| 849 |
# Pillow closes the underlying file descriptor. |
| 850 |
>>> form.is_valid() |
| 851 |
True |
| 852 |
>>> image_field = form.cleaned_data["img"] |
| 853 |
>>> image_field.image |
| 854 |
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=191x287 at 0x7F5985045C18> |
| 855 |
>>> image_field.image.width |
| 856 |
191 |
| 857 |
>>> image_field.image.height |
| 858 |
287 |
| 859 |
>>> image_field.image.format |
| 860 |
'PNG' |
| 861 |
>>> image_field.image.getdata() |
| 862 |
# Raises AttributeError: 'NoneType' object has no attribute 'seek'. |
| 863 |
>>> image = Image.open(image_field) |
| 864 |
>>> image.getdata() |
| 865 |
<ImagingCore object at 0x7f5984f874b0> |
| 866 |
|
| 867 |
Additionally, ``UploadedFile.content_type`` will be updated with the |
| 868 |
image's content type if Pillow can determine it, otherwise it will be set |
| 869 |
to ``None``. |
| 870 |
|
| 871 |
.. _Image: https://pillow.readthedocs.io/en/latest/reference/Image.html |
| 872 |
|
| 873 |
``IntegerField`` |
| 874 |
---------------- |
| 875 |
|
| 876 |
.. class:: IntegerField(**kwargs) |
| 877 |
|
| 878 |
* Default widget: :class:`NumberInput` when :attr:`Field.localize` is |
| 879 |
``False``, else :class:`TextInput`. |
| 880 |
* Empty value: ``None`` |
| 881 |
* Normalizes to: A Python integer. |
| 882 |
* Validates that the given value is an integer. Uses |
| 883 |
:class:`~django.core.validators.MaxValueValidator` and |
| 884 |
:class:`~django.core.validators.MinValueValidator` if ``max_value`` and |
| 885 |
``min_value`` are provided. Uses |
| 886 |
:class:`~django.core.validators.StepValueValidator` if ``step_size`` is |
| 887 |
provided. Leading and trailing whitespace is allowed, as in Python's |
| 888 |
``int()`` function. |
| 889 |
* Error message keys: ``required``, ``invalid``, ``max_value``, |
| 890 |
``min_value``, ``step_size`` |
| 891 |
|
| 892 |
The ``max_value``, ``min_value`` and ``step_size`` error messages may |
| 893 |
contain ``%(limit_value)s``, which will be substituted by the appropriate |
| 894 |
limit. |
| 895 |
|
| 896 |
Takes three optional arguments for validation: |
| 897 |
|
| 898 |
.. attribute:: max_value |
| 899 |
.. attribute:: min_value |
| 900 |
|
| 901 |
These control the range of values permitted in the field. |
| 902 |
|
| 903 |
.. attribute:: step_size |
| 904 |
|
| 905 |
Limit valid inputs to an integral multiple of ``step_size``. If |
| 906 |
``min_value`` is also provided, it's added as an offset to determine if |
| 907 |
the step size matches. |
| 908 |
|
| 909 |
``JSONField`` |
| 910 |
------------- |
| 911 |
|
| 912 |
.. class:: JSONField(encoder=None, decoder=None, **kwargs) |
| 913 |
|
| 914 |
A field which accepts JSON encoded data for a |
| 915 |
:class:`~django.db.models.JSONField`. |
| 916 |
|
| 917 |
* Default widget: :class:`Textarea` |
| 918 |
* Empty value: ``None`` |
| 919 |
* Normalizes to: A Python representation of the JSON value (usually as a |
| 920 |
``dict``, ``list``, or ``None``), depending on :attr:`JSONField.decoder`. |
| 921 |
* Validates that the given value is a valid JSON. |
| 922 |
* Error message keys: ``required``, ``invalid`` |
| 923 |
|
| 924 |
Takes two optional arguments: |
| 925 |
|
| 926 |
.. attribute:: encoder |
| 927 |
|
| 928 |
A :py:class:`json.JSONEncoder` subclass to serialize data types not |
| 929 |
supported by the standard JSON serializer (e.g. ``datetime.datetime`` |
| 930 |
or :class:`~python:uuid.UUID`). For example, you can use the |
| 931 |
:class:`~django.core.serializers.json.DjangoJSONEncoder` class. |
| 932 |
|
| 933 |
Defaults to ``json.JSONEncoder``. |
| 934 |
|
| 935 |
.. attribute:: decoder |
| 936 |
|
| 937 |
A :py:class:`json.JSONDecoder` subclass to deserialize the input. Your |
| 938 |
deserialization may need to account for the fact that you can't be |
| 939 |
certain of the input type. For example, you run the risk of returning a |
| 940 |
``datetime`` that was actually a string that just happened to be in the |
| 941 |
same format chosen for ``datetime``\s. |
| 942 |
|
| 943 |
The ``decoder`` can be used to validate the input. If |
| 944 |
:py:class:`json.JSONDecodeError` is raised during the deserialization, |
| 945 |
a ``ValidationError`` will be raised. |
| 946 |
|
| 947 |
Defaults to ``json.JSONDecoder``. |
| 948 |
|
| 949 |
.. note:: |
| 950 |
|
| 951 |
If you use a :class:`ModelForm <django.forms.ModelForm>`, the |
| 952 |
``encoder`` and ``decoder`` from :class:`~django.db.models.JSONField` |
| 953 |
will be used. |
| 954 |
|
| 955 |
.. admonition:: User friendly forms |
| 956 |
|
| 957 |
``JSONField`` is not particularly user friendly in most cases. However, |
| 958 |
it is a useful way to format data from a client-side widget for |
| 959 |
submission to the server. |
| 960 |
|
| 961 |
``MultipleChoiceField`` |
| 962 |
----------------------- |
| 963 |
|
| 964 |
.. class:: MultipleChoiceField(**kwargs) |
| 965 |
|
| 966 |
* Default widget: :class:`SelectMultiple` |
| 967 |
* Empty value: ``[]`` (an empty list) |
| 968 |
* Normalizes to: A list of strings. |
| 969 |
* Validates that every value in the given list of values exists in the list |
| 970 |
of choices. |
| 971 |
* Error message keys: ``required``, ``invalid_choice``, ``invalid_list`` |
| 972 |
|
| 973 |
The ``invalid_choice`` error message may contain ``%(value)s``, which will be |
| 974 |
replaced with the selected choice. |
| 975 |
|
| 976 |
Takes one extra required argument, ``choices``, as for :class:`ChoiceField`. |
| 977 |
|
| 978 |
``NullBooleanField`` |
| 979 |
-------------------- |
| 980 |
|
| 981 |
.. class:: NullBooleanField(**kwargs) |
| 982 |
|
| 983 |
* Default widget: :class:`NullBooleanSelect` |
| 984 |
* Empty value: ``None`` |
| 985 |
* Normalizes to: A Python ``True``, ``False`` or ``None`` value. |
| 986 |
* Validates nothing (i.e., it never raises a ``ValidationError``). |
| 987 |
|
| 988 |
``NullBooleanField`` may be used with widgets such as |
| 989 |
:class:`~django.forms.Select` or :class:`~django.forms.RadioSelect` |
| 990 |
by providing the widget ``choices``:: |
| 991 |
|
| 992 |
NullBooleanField( |
| 993 |
widget=Select( |
| 994 |
choices=[ |
| 995 |
("", "Unknown"), |
| 996 |
(True, "Yes"), |
| 997 |
(False, "No"), |
| 998 |
] |
| 999 |
) |
| 1000 |
) |
| 1001 |
|
| 1002 |
``RegexField`` |
| 1003 |
-------------- |
| 1004 |
|
| 1005 |
.. class:: RegexField(**kwargs) |
| 1006 |
|
| 1007 |
* Default widget: :class:`TextInput` |
| 1008 |
* Empty value: Whatever you've given as ``empty_value``. |
| 1009 |
* Normalizes to: A string. |
| 1010 |
* Uses :class:`~django.core.validators.RegexValidator` to validate that |
| 1011 |
the given value matches a certain regular expression. |
| 1012 |
* Error message keys: ``required``, ``invalid`` |
| 1013 |
|
| 1014 |
Takes one required argument: |
| 1015 |
|
| 1016 |
.. attribute:: regex |
| 1017 |
|
| 1018 |
A regular expression specified either as a string or a compiled regular |
| 1019 |
expression object. |
| 1020 |
|
| 1021 |
Also takes ``max_length``, ``min_length``, ``strip``, and ``empty_value`` |
| 1022 |
which work just as they do for :class:`CharField`. |
| 1023 |
|
| 1024 |
.. attribute:: strip |
| 1025 |
|
| 1026 |
Defaults to ``False``. If enabled, stripping will be applied before the |
| 1027 |
regex validation. |
| 1028 |
|
| 1029 |
``SlugField`` |
| 1030 |
------------- |
| 1031 |
|
| 1032 |
.. class:: SlugField(**kwargs) |
| 1033 |
|
| 1034 |
* Default widget: :class:`TextInput` |
| 1035 |
* Empty value: Whatever you've given as :attr:`empty_value`. |
| 1036 |
* Normalizes to: A string. |
| 1037 |
* Uses :class:`~django.core.validators.validate_slug` or |
| 1038 |
:class:`~django.core.validators.validate_unicode_slug` to validate that |
| 1039 |
the given value contains only letters, numbers, underscores, and hyphens. |
| 1040 |
* Error messages: ``required``, ``invalid`` |
| 1041 |
|
| 1042 |
This field is intended for use in representing a model |
| 1043 |
:class:`~django.db.models.SlugField` in forms. |
| 1044 |
|
| 1045 |
Takes two optional parameters: |
| 1046 |
|
| 1047 |
.. attribute:: allow_unicode |
| 1048 |
|
| 1049 |
A boolean instructing the field to accept Unicode letters in addition |
| 1050 |
to ASCII letters. Defaults to ``False``. |
| 1051 |
|
| 1052 |
.. attribute:: empty_value |
| 1053 |
|
| 1054 |
The value to use to represent "empty". Defaults to an empty string. |
| 1055 |
|
| 1056 |
``TimeField`` |
| 1057 |
------------- |
| 1058 |
|
| 1059 |
.. class:: TimeField(**kwargs) |
| 1060 |
|
| 1061 |
* Default widget: :class:`TimeInput` |
| 1062 |
* Empty value: ``None`` |
| 1063 |
* Normalizes to: A Python ``datetime.time`` object. |
| 1064 |
* Validates that the given value is either a ``datetime.time`` or string |
| 1065 |
formatted in a particular time format. |
| 1066 |
* Error message keys: ``required``, ``invalid`` |
| 1067 |
|
| 1068 |
Takes one optional argument: |
| 1069 |
|
| 1070 |
.. attribute:: input_formats |
| 1071 |
|
| 1072 |
An iterable of formats used to attempt to convert a string to a valid |
| 1073 |
``datetime.time`` object. |
| 1074 |
|
| 1075 |
If no ``input_formats`` argument is provided, the default input formats are |
| 1076 |
taken from the active locale format ``TIME_INPUT_FORMATS`` key, or from |
| 1077 |
:setting:`TIME_INPUT_FORMATS` if localization is disabled. See also |
| 1078 |
:doc:`format localization </topics/i18n/formatting>`. |
| 1079 |
|
| 1080 |
``TypedChoiceField`` |
| 1081 |
-------------------- |
| 1082 |
|
| 1083 |
.. class:: TypedChoiceField(**kwargs) |
| 1084 |
|
| 1085 |
Just like a :class:`ChoiceField`, except :class:`TypedChoiceField` takes two |
| 1086 |
extra arguments, :attr:`coerce` and :attr:`empty_value`. |
| 1087 |
|
| 1088 |
* Default widget: :class:`Select` |
| 1089 |
* Empty value: Whatever you've given as :attr:`empty_value`. |
| 1090 |
* Normalizes to: A value of the type provided by the :attr:`coerce` |
| 1091 |
argument. |
| 1092 |
* Validates that the given value exists in the list of choices and can be |
| 1093 |
coerced. |
| 1094 |
* Error message keys: ``required``, ``invalid_choice`` |
| 1095 |
|
| 1096 |
Takes extra arguments: |
| 1097 |
|
| 1098 |
.. attribute:: coerce |
| 1099 |
|
| 1100 |
A function that takes one argument and returns a coerced value. Examples |
| 1101 |
include the built-in ``int``, ``float``, ``bool`` and other types. Defaults |
| 1102 |
to an identity function. Note that coercion happens after input |
| 1103 |
validation, so it is possible to coerce to a value not present in |
| 1104 |
``choices``. |
| 1105 |
|
| 1106 |
.. attribute:: empty_value |
| 1107 |
|
| 1108 |
The value to use to represent "empty." Defaults to the empty string; |
| 1109 |
``None`` is another common choice here. Note that this value will not be |
| 1110 |
coerced by the function given in the ``coerce`` argument, so choose it |
| 1111 |
accordingly. |
| 1112 |
|
| 1113 |
``TypedMultipleChoiceField`` |
| 1114 |
---------------------------- |
| 1115 |
|
| 1116 |
.. class:: TypedMultipleChoiceField(**kwargs) |
| 1117 |
|
| 1118 |
Just like a :class:`MultipleChoiceField`, except :class:`TypedMultipleChoiceField` |
| 1119 |
takes two extra arguments, ``coerce`` and ``empty_value``. |
| 1120 |
|
| 1121 |
* Default widget: :class:`SelectMultiple` |
| 1122 |
* Empty value: Whatever you've given as ``empty_value`` |
| 1123 |
* Normalizes to: A list of values of the type provided by the ``coerce`` |
| 1124 |
argument. |
| 1125 |
* Validates that the given values exists in the list of choices and can be |
| 1126 |
coerced. |
| 1127 |
* Error message keys: ``required``, ``invalid_choice`` |
| 1128 |
|
| 1129 |
The ``invalid_choice`` error message may contain ``%(value)s``, which will be |
| 1130 |
replaced with the selected choice. |
| 1131 |
|
| 1132 |
Takes two extra arguments, ``coerce`` and ``empty_value``, as for |
| 1133 |
:class:`TypedChoiceField`. |
| 1134 |
|
| 1135 |
``URLField`` |
| 1136 |
------------ |
| 1137 |
|
| 1138 |
.. class:: URLField(**kwargs) |
| 1139 |
|
| 1140 |
* Default widget: :class:`URLInput` |
| 1141 |
* Empty value: Whatever you've given as ``empty_value``. |
| 1142 |
* Normalizes to: A string. |
| 1143 |
* Uses :class:`~django.core.validators.URLValidator` to validate that the |
| 1144 |
given value is a valid URL. |
| 1145 |
* Error message keys: ``required``, ``invalid`` |
| 1146 |
|
| 1147 |
Has the optional arguments ``max_length``, ``min_length``, ``empty_value`` |
| 1148 |
which work just as they do for :class:`CharField`, and one more argument: |
| 1149 |
|
| 1150 |
.. attribute:: assume_scheme |
| 1151 |
|
| 1152 |
The scheme assumed for URLs provided without one. Defaults to |
| 1153 |
``"http"``. For example, if ``assume_scheme`` is ``"https"`` and the |
| 1154 |
provided value is ``"example.com"``, the normalized value will be |
| 1155 |
``"https://example.com"``. |
| 1156 |
|
| 1157 |
.. deprecated:: 5.0 |
| 1158 |
|
| 1159 |
The default value for ``assume_scheme`` will change from ``"http"`` to |
| 1160 |
``"https"`` in Django 6.0. Set :setting:`FORMS_URLFIELD_ASSUME_HTTPS` |
| 1161 |
transitional setting to ``True`` to opt into using ``"https"`` during |
| 1162 |
the Django 5.x release cycle. |
| 1163 |
|
| 1164 |
``UUIDField`` |
| 1165 |
------------- |
| 1166 |
|
| 1167 |
.. class:: UUIDField(**kwargs) |
| 1168 |
|
| 1169 |
* Default widget: :class:`TextInput` |
| 1170 |
* Empty value: ``None`` |
| 1171 |
* Normalizes to: A :class:`~python:uuid.UUID` object. |
| 1172 |
* Error message keys: ``required``, ``invalid`` |
| 1173 |
|
| 1174 |
This field will accept any string format accepted as the ``hex`` argument |
| 1175 |
to the :class:`~python:uuid.UUID` constructor. |
| 1176 |
|
| 1177 |
Slightly complex built-in ``Field`` classes |
| 1178 |
=========================================== |
| 1179 |
|
| 1180 |
``ComboField`` |
| 1181 |
-------------- |
| 1182 |
|
| 1183 |
.. class:: ComboField(**kwargs) |
| 1184 |
|
| 1185 |
* Default widget: :class:`TextInput` |
| 1186 |
* Empty value: ``''`` (an empty string) |
| 1187 |
* Normalizes to: A string. |
| 1188 |
* Validates the given value against each of the fields specified |
| 1189 |
as an argument to the ``ComboField``. |
| 1190 |
* Error message keys: ``required``, ``invalid`` |
| 1191 |
|
| 1192 |
Takes one extra required argument: |
| 1193 |
|
| 1194 |
.. attribute:: fields |
| 1195 |
|
| 1196 |
The list of fields that should be used to validate the field's value (in |
| 1197 |
the order in which they are provided). |
| 1198 |
|
| 1199 |
.. code-block:: pycon |
| 1200 |
|
| 1201 |
>>> from django.forms import ComboField |
| 1202 |
>>> f = ComboField(fields=[CharField(max_length=20), EmailField()]) |
| 1203 |
>>> f.clean("[email protected]") |
| 1204 |
'[email protected]' |
| 1205 |
>>> f.clean("[email protected]") |
| 1206 |
Traceback (most recent call last): |
| 1207 |
... |
| 1208 |
ValidationError: ['Ensure this value has at most 20 characters (it has 28).'] |
| 1209 |
|
| 1210 |
``MultiValueField`` |
| 1211 |
------------------- |
| 1212 |
|
| 1213 |
.. class:: MultiValueField(fields=(), **kwargs) |
| 1214 |
|
| 1215 |
* Default widget: :class:`TextInput` |
| 1216 |
* Empty value: ``''`` (an empty string) |
| 1217 |
* Normalizes to: the type returned by the ``compress`` method of the subclass. |
| 1218 |
* Validates the given value against each of the fields specified |
| 1219 |
as an argument to the ``MultiValueField``. |
| 1220 |
* Error message keys: ``required``, ``invalid``, ``incomplete`` |
| 1221 |
|
| 1222 |
Aggregates the logic of multiple fields that together produce a single |
| 1223 |
value. |
| 1224 |
|
| 1225 |
This field is abstract and must be subclassed. In contrast with the |
| 1226 |
single-value fields, subclasses of :class:`MultiValueField` must not |
| 1227 |
implement :meth:`~django.forms.Field.clean` but instead - implement |
| 1228 |
:meth:`~MultiValueField.compress`. |
| 1229 |
|
| 1230 |
Takes one extra required argument: |
| 1231 |
|
| 1232 |
.. attribute:: fields |
| 1233 |
|
| 1234 |
A tuple of fields whose values are cleaned and subsequently combined |
| 1235 |
into a single value. Each value of the field is cleaned by the |
| 1236 |
corresponding field in ``fields`` -- the first value is cleaned by the |
| 1237 |
first field, the second value is cleaned by the second field, etc. |
| 1238 |
Once all fields are cleaned, the list of clean values is combined into |
| 1239 |
a single value by :meth:`~MultiValueField.compress`. |
| 1240 |
|
| 1241 |
Also takes some optional arguments: |
| 1242 |
|
| 1243 |
.. attribute:: require_all_fields |
| 1244 |
|
| 1245 |
Defaults to ``True``, in which case a ``required`` validation error |
| 1246 |
will be raised if no value is supplied for any field. |
| 1247 |
|
| 1248 |
When set to ``False``, the :attr:`Field.required` attribute can be set |
| 1249 |
to ``False`` for individual fields to make them optional. If no value |
| 1250 |
is supplied for a required field, an ``incomplete`` validation error |
| 1251 |
will be raised. |
| 1252 |
|
| 1253 |
A default ``incomplete`` error message can be defined on the |
| 1254 |
:class:`MultiValueField` subclass, or different messages can be defined |
| 1255 |
on each individual field. For example:: |
| 1256 |
|
| 1257 |
from django.core.validators import RegexValidator |
| 1258 |
|
| 1259 |
|
| 1260 |
class PhoneField(MultiValueField): |
| 1261 |
def __init__(self, **kwargs): |
| 1262 |
# Define one message for all fields. |
| 1263 |
error_messages = { |
| 1264 |
"incomplete": "Enter a country calling code and a phone number.", |
| 1265 |
} |
| 1266 |
# Or define a different message for each field. |
| 1267 |
fields = ( |
| 1268 |
CharField( |
| 1269 |
error_messages={"incomplete": "Enter a country calling code."}, |
| 1270 |
validators=[ |
| 1271 |
RegexValidator(r"^[0-9]+$", "Enter a valid country calling code."), |
| 1272 |
], |
| 1273 |
), |
| 1274 |
CharField( |
| 1275 |
error_messages={"incomplete": "Enter a phone number."}, |
| 1276 |
validators=[RegexValidator(r"^[0-9]+$", "Enter a valid phone number.")], |
| 1277 |
), |
| 1278 |
CharField( |
| 1279 |
validators=[RegexValidator(r"^[0-9]+$", "Enter a valid extension.")], |
| 1280 |
required=False, |
| 1281 |
), |
| 1282 |
) |
| 1283 |
super().__init__( |
| 1284 |
error_messages=error_messages, |
| 1285 |
fields=fields, |
| 1286 |
require_all_fields=False, |
| 1287 |
**kwargs |
| 1288 |
) |
| 1289 |
|
| 1290 |
.. attribute:: MultiValueField.widget |
| 1291 |
|
| 1292 |
Must be a subclass of :class:`django.forms.MultiWidget`. |
| 1293 |
Default value is :class:`~django.forms.TextInput`, which |
| 1294 |
probably is not very useful in this case. |
| 1295 |
|
| 1296 |
.. method:: compress(data_list) |
| 1297 |
|
| 1298 |
Takes a list of valid values and returns a "compressed" version of |
| 1299 |
those values -- in a single value. For example, |
| 1300 |
:class:`SplitDateTimeField` is a subclass which combines a time field |
| 1301 |
and a date field into a ``datetime`` object. |
| 1302 |
|
| 1303 |
This method must be implemented in the subclasses. |
| 1304 |
|
| 1305 |
``SplitDateTimeField`` |
| 1306 |
---------------------- |
| 1307 |
|
| 1308 |
.. class:: SplitDateTimeField(**kwargs) |
| 1309 |
|
| 1310 |
* Default widget: :class:`SplitDateTimeWidget` |
| 1311 |
* Empty value: ``None`` |
| 1312 |
* Normalizes to: A Python ``datetime.datetime`` object. |
| 1313 |
* Validates that the given value is a ``datetime.datetime`` or string |
| 1314 |
formatted in a particular datetime format. |
| 1315 |
* Error message keys: ``required``, ``invalid``, ``invalid_date``, |
| 1316 |
``invalid_time`` |
| 1317 |
|
| 1318 |
Takes two optional arguments: |
| 1319 |
|
| 1320 |
.. attribute:: input_date_formats |
| 1321 |
|
| 1322 |
A list of formats used to attempt to convert a string to a valid |
| 1323 |
``datetime.date`` object. |
| 1324 |
|
| 1325 |
If no ``input_date_formats`` argument is provided, the default input formats |
| 1326 |
for :class:`DateField` are used. |
| 1327 |
|
| 1328 |
.. attribute:: input_time_formats |
| 1329 |
|
| 1330 |
A list of formats used to attempt to convert a string to a valid |
| 1331 |
``datetime.time`` object. |
| 1332 |
|
| 1333 |
If no ``input_time_formats`` argument is provided, the default input formats |
| 1334 |
for :class:`TimeField` are used. |
| 1335 |
|
| 1336 |
.. _fields-which-handle-relationships: |
| 1337 |
|
| 1338 |
Fields which handle relationships |
| 1339 |
================================= |
| 1340 |
|
| 1341 |
Two fields are available for representing relationships between |
| 1342 |
models: :class:`ModelChoiceField` and |
| 1343 |
:class:`ModelMultipleChoiceField`. Both of these fields require a |
| 1344 |
single ``queryset`` parameter that is used to create the choices for |
| 1345 |
the field. Upon form validation, these fields will place either one |
| 1346 |
model object (in the case of ``ModelChoiceField``) or multiple model |
| 1347 |
objects (in the case of ``ModelMultipleChoiceField``) into the |
| 1348 |
``cleaned_data`` dictionary of the form. |
| 1349 |
|
| 1350 |
For more complex uses, you can specify ``queryset=None`` when declaring the |
| 1351 |
form field and then populate the ``queryset`` in the form's ``__init__()`` |
| 1352 |
method:: |
| 1353 |
|
| 1354 |
class FooMultipleChoiceForm(forms.Form): |
| 1355 |
foo_select = forms.ModelMultipleChoiceField(queryset=None) |
| 1356 |
|
| 1357 |
def __init__(self, *args, **kwargs): |
| 1358 |
super().__init__(*args, **kwargs) |
| 1359 |
self.fields["foo_select"].queryset = ... |
| 1360 |
|
| 1361 |
Both ``ModelChoiceField`` and ``ModelMultipleChoiceField`` have an ``iterator`` |
| 1362 |
attribute which specifies the class used to iterate over the queryset when |
| 1363 |
generating choices. See :ref:`iterating-relationship-choices` for details. |
| 1364 |
|
| 1365 |
``ModelChoiceField`` |
| 1366 |
-------------------- |
| 1367 |
|
| 1368 |
.. class:: ModelChoiceField(**kwargs) |
| 1369 |
|
| 1370 |
* Default widget: :class:`Select` |
| 1371 |
* Empty value: ``None`` |
| 1372 |
* Normalizes to: A model instance. |
| 1373 |
* Validates that the given id exists in the queryset. |
| 1374 |
* Error message keys: ``required``, ``invalid_choice`` |
| 1375 |
|
| 1376 |
The ``invalid_choice`` error message may contain ``%(value)s``, which will |
| 1377 |
be replaced with the selected choice. |
| 1378 |
|
| 1379 |
Allows the selection of a single model object, suitable for representing a |
| 1380 |
foreign key. Note that the default widget for ``ModelChoiceField`` becomes |
| 1381 |
impractical when the number of entries increases. You should avoid using it |
| 1382 |
for more than 100 items. |
| 1383 |
|
| 1384 |
A single argument is required: |
| 1385 |
|
| 1386 |
.. attribute:: queryset |
| 1387 |
|
| 1388 |
A ``QuerySet`` of model objects from which the choices for the field |
| 1389 |
are derived and which is used to validate the user's selection. It's |
| 1390 |
evaluated when the form is rendered. |
| 1391 |
|
| 1392 |
``ModelChoiceField`` also takes several optional arguments: |
| 1393 |
|
| 1394 |
.. attribute:: empty_label |
| 1395 |
|
| 1396 |
By default the ``<select>`` widget used by ``ModelChoiceField`` will have an |
| 1397 |
empty choice at the top of the list. You can change the text of this |
| 1398 |
label (which is ``"---------"`` by default) with the ``empty_label`` |
| 1399 |
attribute, or you can disable the empty label entirely by setting |
| 1400 |
``empty_label`` to ``None``:: |
| 1401 |
|
| 1402 |
# A custom empty label |
| 1403 |
field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)") |
| 1404 |
|
| 1405 |
# No empty label |
| 1406 |
field2 = forms.ModelChoiceField(queryset=..., empty_label=None) |
| 1407 |
|
| 1408 |
Note that no empty choice is created (regardless of the value of |
| 1409 |
``empty_label``) if a ``ModelChoiceField`` is required and has a |
| 1410 |
default initial value, or a ``widget`` is set to |
| 1411 |
:class:`~django.forms.RadioSelect` and the |
| 1412 |
:attr:`~ModelChoiceField.blank` argument is ``False``. |
| 1413 |
|
| 1414 |
.. attribute:: to_field_name |
| 1415 |
|
| 1416 |
This optional argument is used to specify the field to use as the value |
| 1417 |
of the choices in the field's widget. Be sure it's a unique field for |
| 1418 |
the model, otherwise the selected value could match more than one |
| 1419 |
object. By default it is set to ``None``, in which case the primary key |
| 1420 |
of each object will be used. For example:: |
| 1421 |
|
| 1422 |
# No custom to_field_name |
| 1423 |
field1 = forms.ModelChoiceField(queryset=...) |
| 1424 |
|
| 1425 |
would yield: |
| 1426 |
|
| 1427 |
.. code-block:: html |
| 1428 |
|
| 1429 |
<select id="id_field1" name="field1"> |
| 1430 |
<option value="obj1.pk">Object1</option> |
| 1431 |
<option value="obj2.pk">Object2</option> |
| 1432 |
... |
| 1433 |
</select> |
| 1434 |
|
| 1435 |
and:: |
| 1436 |
|
| 1437 |
# to_field_name provided |
| 1438 |
field2 = forms.ModelChoiceField(queryset=..., to_field_name="name") |
| 1439 |
|
| 1440 |
would yield: |
| 1441 |
|
| 1442 |
.. code-block:: html |
| 1443 |
|
| 1444 |
<select id="id_field2" name="field2"> |
| 1445 |
<option value="obj1.name">Object1</option> |
| 1446 |
<option value="obj2.name">Object2</option> |
| 1447 |
... |
| 1448 |
</select> |
| 1449 |
|
| 1450 |
.. attribute:: blank |
| 1451 |
|
| 1452 |
When using the :class:`~django.forms.RadioSelect` widget, this optional |
| 1453 |
boolean argument determines whether an empty choice is created. By |
| 1454 |
default, ``blank`` is ``False``, in which case no empty choice is |
| 1455 |
created. |
| 1456 |
|
| 1457 |
``ModelChoiceField`` also has the attribute: |
| 1458 |
|
| 1459 |
.. attribute:: iterator |
| 1460 |
|
| 1461 |
The iterator class used to generate field choices from ``queryset``. By |
| 1462 |
default, :class:`ModelChoiceIterator`. |
| 1463 |
|
| 1464 |
The ``__str__()`` method of the model will be called to generate string |
| 1465 |
representations of the objects for use in the field's choices. To provide |
| 1466 |
customized representations, subclass ``ModelChoiceField`` and override |
| 1467 |
``label_from_instance``. This method will receive a model object and should |
| 1468 |
return a string suitable for representing it. For example:: |
| 1469 |
|
| 1470 |
from django.forms import ModelChoiceField |
| 1471 |
|
| 1472 |
|
| 1473 |
class MyModelChoiceField(ModelChoiceField): |
| 1474 |
def label_from_instance(self, obj): |
| 1475 |
return "My Object #%i" % obj.id |
| 1476 |
|
| 1477 |
``ModelMultipleChoiceField`` |
| 1478 |
---------------------------- |
| 1479 |
|
| 1480 |
.. class:: ModelMultipleChoiceField(**kwargs) |
| 1481 |
|
| 1482 |
* Default widget: :class:`SelectMultiple` |
| 1483 |
* Empty value: An empty ``QuerySet`` (``self.queryset.none()``) |
| 1484 |
* Normalizes to: A ``QuerySet`` of model instances. |
| 1485 |
* Validates that every id in the given list of values exists in the |
| 1486 |
queryset. |
| 1487 |
* Error message keys: ``required``, ``invalid_list``, ``invalid_choice``, |
| 1488 |
``invalid_pk_value`` |
| 1489 |
|
| 1490 |
The ``invalid_choice`` message may contain ``%(value)s`` and the |
| 1491 |
``invalid_pk_value`` message may contain ``%(pk)s``, which will be |
| 1492 |
substituted by the appropriate values. |
| 1493 |
|
| 1494 |
Allows the selection of one or more model objects, suitable for |
| 1495 |
representing a many-to-many relation. As with :class:`ModelChoiceField`, |
| 1496 |
you can use ``label_from_instance`` to customize the object |
| 1497 |
representations. |
| 1498 |
|
| 1499 |
A single argument is required: |
| 1500 |
|
| 1501 |
.. attribute:: queryset |
| 1502 |
|
| 1503 |
Same as :class:`ModelChoiceField.queryset`. |
| 1504 |
|
| 1505 |
Takes one optional argument: |
| 1506 |
|
| 1507 |
.. attribute:: to_field_name |
| 1508 |
|
| 1509 |
Same as :class:`ModelChoiceField.to_field_name`. |
| 1510 |
|
| 1511 |
``ModelMultipleChoiceField`` also has the attribute: |
| 1512 |
|
| 1513 |
.. attribute:: iterator |
| 1514 |
|
| 1515 |
Same as :class:`ModelChoiceField.iterator`. |
| 1516 |
|
| 1517 |
.. _iterating-relationship-choices: |
| 1518 |
|
| 1519 |
Iterating relationship choices |
| 1520 |
------------------------------ |
| 1521 |
|
| 1522 |
By default, :class:`ModelChoiceField` and :class:`ModelMultipleChoiceField` use |
| 1523 |
:class:`ModelChoiceIterator` to generate their field ``choices``. |
| 1524 |
|
| 1525 |
When iterated, ``ModelChoiceIterator`` yields 2-tuple choices containing |
| 1526 |
:class:`ModelChoiceIteratorValue` instances as the first ``value`` element in |
| 1527 |
each choice. ``ModelChoiceIteratorValue`` wraps the choice value while |
| 1528 |
maintaining a reference to the source model instance that can be used in custom |
| 1529 |
widget implementations, for example, to add `data-* attributes`_ to |
| 1530 |
``<option>`` elements. |
| 1531 |
|
| 1532 |
.. _`data-* attributes`: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-* |
| 1533 |
|
| 1534 |
For example, consider the following models:: |
| 1535 |
|
| 1536 |
from django.db import models |
| 1537 |
|
| 1538 |
|
| 1539 |
class Topping(models.Model): |
| 1540 |
name = models.CharField(max_length=100) |
| 1541 |
price = models.DecimalField(decimal_places=2, max_digits=6) |
| 1542 |
|
| 1543 |
def __str__(self): |
| 1544 |
return self.name |
| 1545 |
|
| 1546 |
|
| 1547 |
class Pizza(models.Model): |
| 1548 |
topping = models.ForeignKey(Topping, on_delete=models.CASCADE) |
| 1549 |
|
| 1550 |
You can use a :class:`~django.forms.Select` widget subclass to include |
| 1551 |
the value of ``Topping.price`` as the HTML attribute ``data-price`` for each |
| 1552 |
``<option>`` element:: |
| 1553 |
|
| 1554 |
from django import forms |
| 1555 |
|
| 1556 |
|
| 1557 |
class ToppingSelect(forms.Select): |
| 1558 |
def create_option( |
| 1559 |
self, name, value, label, selected, index, subindex=None, attrs=None |
| 1560 |
): |
| 1561 |
option = super().create_option( |
| 1562 |
name, value, label, selected, index, subindex, attrs |
| 1563 |
) |
| 1564 |
if value: |
| 1565 |
option["attrs"]["data-price"] = value.instance.price |
| 1566 |
return option |
| 1567 |
|
| 1568 |
|
| 1569 |
class PizzaForm(forms.ModelForm): |
| 1570 |
class Meta: |
| 1571 |
model = Pizza |
| 1572 |
fields = ["topping"] |
| 1573 |
widgets = {"topping": ToppingSelect} |
| 1574 |
|
| 1575 |
This will render the ``Pizza.topping`` select as: |
| 1576 |
|
| 1577 |
.. code-block:: html |
| 1578 |
|
| 1579 |
<select id="id_topping" name="topping" required> |
| 1580 |
<option value="" selected>---------</option> |
| 1581 |
<option value="1" data-price="1.50">mushrooms</option> |
| 1582 |
<option value="2" data-price="1.25">onions</option> |
| 1583 |
<option value="3" data-price="1.75">peppers</option> |
| 1584 |
<option value="4" data-price="2.00">pineapple</option> |
| 1585 |
</select> |
| 1586 |
|
| 1587 |
For more advanced usage you may subclass ``ModelChoiceIterator`` in order to |
| 1588 |
customize the yielded 2-tuple choices. |
| 1589 |
|
| 1590 |
``ModelChoiceIterator`` |
| 1591 |
~~~~~~~~~~~~~~~~~~~~~~~ |
| 1592 |
|
| 1593 |
.. class:: ModelChoiceIterator(field) |
| 1594 |
|
| 1595 |
The default class assigned to the ``iterator`` attribute of |
| 1596 |
:class:`ModelChoiceField` and :class:`ModelMultipleChoiceField`. An |
| 1597 |
iterable that yields 2-tuple choices from the queryset. |
| 1598 |
|
| 1599 |
A single argument is required: |
| 1600 |
|
| 1601 |
.. attribute:: field |
| 1602 |
|
| 1603 |
The instance of ``ModelChoiceField`` or ``ModelMultipleChoiceField`` to |
| 1604 |
iterate and yield choices. |
| 1605 |
|
| 1606 |
``ModelChoiceIterator`` has the following method: |
| 1607 |
|
| 1608 |
.. method:: __iter__() |
| 1609 |
|
| 1610 |
Yields 2-tuple choices, in the ``(value, label)`` format used by |
| 1611 |
:attr:`ChoiceField.choices`. The first ``value`` element is a |
| 1612 |
:class:`ModelChoiceIteratorValue` instance. |
| 1613 |
|
| 1614 |
``ModelChoiceIteratorValue`` |
| 1615 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 1616 |
|
| 1617 |
.. class:: ModelChoiceIteratorValue(value, instance) |
| 1618 |
|
| 1619 |
Two arguments are required: |
| 1620 |
|
| 1621 |
.. attribute:: value |
| 1622 |
|
| 1623 |
The value of the choice. This value is used to render the ``value`` |
| 1624 |
attribute of an HTML ``<option>`` element. |
| 1625 |
|
| 1626 |
.. attribute:: instance |
| 1627 |
|
| 1628 |
The model instance from the queryset. The instance can be accessed in |
| 1629 |
custom ``ChoiceWidget.create_option()`` implementations to adjust the |
| 1630 |
rendered HTML. |
| 1631 |
|
| 1632 |
``ModelChoiceIteratorValue`` has the following method: |
| 1633 |
|
| 1634 |
.. method:: __str__() |
| 1635 |
|
| 1636 |
Return ``value`` as a string to be rendered in HTML. |
| 1637 |
|
| 1638 |
Creating custom fields |
| 1639 |
====================== |
| 1640 |
|
| 1641 |
If the built-in ``Field`` classes don't meet your needs, you can create custom |
| 1642 |
``Field`` classes. To do this, create a subclass of ``django.forms.Field``. Its |
| 1643 |
only requirements are that it implement a ``clean()`` method and that its |
| 1644 |
``__init__()`` method accept the core arguments mentioned above (``required``, |
| 1645 |
``label``, ``initial``, ``widget``, ``help_text``). |
| 1646 |
|
| 1647 |
You can also customize how a field will be accessed by overriding |
| 1648 |
:attr:`~django.forms.Field.bound_field_class` or override |
| 1649 |
:meth:`.Field.get_bound_field()` if you need more flexibility when creating |
| 1650 |
the ``BoundField``: |
| 1651 |
|
| 1652 |
.. method:: Field.get_bound_field(form, field_name) |
| 1653 |
|
| 1654 |
Takes an instance of :class:`~django.forms.Form` and the name of the field. |
| 1655 |
The returned :class:`.BoundField` instance will be used when accessing the |
| 1656 |
field in a template. |
| 1657 |
|
| 1658 |
See :ref:`custom-boundfield` for examples of overriding a ``BoundField``. |