fields.txt 57 KB

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