2
0

fields.txt 57 KB

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