fields.txt 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638
  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``, ``max_length``
  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 three 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. .. attribute:: max_length
  585. Defaults to 39, and behaves the same way as it does for
  586. :class:`CharField`.
  587. .. versionchanged:: 4.2.18
  588. The default value for ``max_length`` was set to 39 characters.
  589. ``ImageField``
  590. --------------
  591. .. class:: ImageField(**kwargs)
  592. * Default widget: :class:`ClearableFileInput`
  593. * Empty value: ``None``
  594. * Normalizes to: An ``UploadedFile`` object that wraps the file content
  595. and file name into a single object.
  596. * Validates that file data has been bound to the form. Also uses
  597. :class:`~django.core.validators.FileExtensionValidator` to validate that
  598. the file extension is supported by Pillow.
  599. * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,
  600. ``invalid_image``
  601. Using an ``ImageField`` requires that :pypi:`pillow` is installed with
  602. support for the image formats you use. If you encounter a ``corrupt image``
  603. error when you upload an image, it usually means that Pillow doesn't
  604. understand its format. To fix this, install the appropriate library and
  605. reinstall Pillow.
  606. When you use an ``ImageField`` on a form, you must also remember to
  607. :ref:`bind the file data to the form <binding-uploaded-files>`.
  608. After the field has been cleaned and validated, the ``UploadedFile``
  609. object will have an additional ``image`` attribute containing the Pillow
  610. `Image`_ instance used to check if the file was a valid image. Pillow
  611. closes the underlying file descriptor after verifying an image, so while
  612. non-image data attributes, such as ``format``, ``height``, and ``width``,
  613. are available, methods that access the underlying image data, such as
  614. ``getdata()`` or ``getpixel()``, cannot be used without reopening the file.
  615. For example:
  616. .. code-block:: pycon
  617. >>> from PIL import Image
  618. >>> from django import forms
  619. >>> from django.core.files.uploadedfile import SimpleUploadedFile
  620. >>> class ImageForm(forms.Form):
  621. ... img = forms.ImageField()
  622. ...
  623. >>> file_data = {"img": SimpleUploadedFile("test.png", b"file data")}
  624. >>> form = ImageForm({}, file_data)
  625. # Pillow closes the underlying file descriptor.
  626. >>> form.is_valid()
  627. True
  628. >>> image_field = form.cleaned_data["img"]
  629. >>> image_field.image
  630. <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=191x287 at 0x7F5985045C18>
  631. >>> image_field.image.width
  632. 191
  633. >>> image_field.image.height
  634. 287
  635. >>> image_field.image.format
  636. 'PNG'
  637. >>> image_field.image.getdata()
  638. # Raises AttributeError: 'NoneType' object has no attribute 'seek'.
  639. >>> image = Image.open(image_field)
  640. >>> image.getdata()
  641. <ImagingCore object at 0x7f5984f874b0>
  642. Additionally, ``UploadedFile.content_type`` will be updated with the
  643. image's content type if Pillow can determine it, otherwise it will be set
  644. to ``None``.
  645. .. _Image: https://pillow.readthedocs.io/en/latest/reference/Image.html
  646. ``IntegerField``
  647. ----------------
  648. .. class:: IntegerField(**kwargs)
  649. * Default widget: :class:`NumberInput` when :attr:`Field.localize` is
  650. ``False``, else :class:`TextInput`.
  651. * Empty value: ``None``
  652. * Normalizes to: A Python integer.
  653. * Validates that the given value is an integer. Uses
  654. :class:`~django.core.validators.MaxValueValidator` and
  655. :class:`~django.core.validators.MinValueValidator` if ``max_value`` and
  656. ``min_value`` are provided. Uses
  657. :class:`~django.core.validators.StepValueValidator` if ``step_size`` is
  658. provided. Leading and trailing whitespace is allowed, as in Python's
  659. ``int()`` function.
  660. * Error message keys: ``required``, ``invalid``, ``max_value``,
  661. ``min_value``, ``step_size``
  662. The ``max_value``, ``min_value`` and ``step_size`` error messages may
  663. contain ``%(limit_value)s``, which will be substituted by the appropriate
  664. limit.
  665. Takes three optional arguments for validation:
  666. .. attribute:: max_value
  667. .. attribute:: min_value
  668. These control the range of values permitted in the field.
  669. .. attribute:: step_size
  670. Limit valid inputs to an integral multiple of ``step_size``. If
  671. ``min_value`` is also provided, it's added as an offset to determine if
  672. the step size matches.
  673. ``JSONField``
  674. -------------
  675. .. class:: JSONField(encoder=None, decoder=None, **kwargs)
  676. A field which accepts JSON encoded data for a
  677. :class:`~django.db.models.JSONField`.
  678. * Default widget: :class:`Textarea`
  679. * Empty value: ``None``
  680. * Normalizes to: A Python representation of the JSON value (usually as a
  681. ``dict``, ``list``, or ``None``), depending on :attr:`JSONField.decoder`.
  682. * Validates that the given value is a valid JSON.
  683. * Error message keys: ``required``, ``invalid``
  684. Takes two optional arguments:
  685. .. attribute:: encoder
  686. A :py:class:`json.JSONEncoder` subclass to serialize data types not
  687. supported by the standard JSON serializer (e.g. ``datetime.datetime``
  688. or :class:`~python:uuid.UUID`). For example, you can use the
  689. :class:`~django.core.serializers.json.DjangoJSONEncoder` class.
  690. Defaults to ``json.JSONEncoder``.
  691. .. attribute:: decoder
  692. A :py:class:`json.JSONDecoder` subclass to deserialize the input. Your
  693. deserialization may need to account for the fact that you can't be
  694. certain of the input type. For example, you run the risk of returning a
  695. ``datetime`` that was actually a string that just happened to be in the
  696. same format chosen for ``datetime``\s.
  697. The ``decoder`` can be used to validate the input. If
  698. :py:class:`json.JSONDecodeError` is raised during the deserialization,
  699. a ``ValidationError`` will be raised.
  700. Defaults to ``json.JSONDecoder``.
  701. .. note::
  702. If you use a :class:`ModelForm <django.forms.ModelForm>`, the
  703. ``encoder`` and ``decoder`` from :class:`~django.db.models.JSONField`
  704. will be used.
  705. .. admonition:: User friendly forms
  706. ``JSONField`` is not particularly user friendly in most cases. However,
  707. it is a useful way to format data from a client-side widget for
  708. submission to the server.
  709. ``MultipleChoiceField``
  710. -----------------------
  711. .. class:: MultipleChoiceField(**kwargs)
  712. * Default widget: :class:`SelectMultiple`
  713. * Empty value: ``[]`` (an empty list)
  714. * Normalizes to: A list of strings.
  715. * Validates that every value in the given list of values exists in the list
  716. of choices.
  717. * Error message keys: ``required``, ``invalid_choice``, ``invalid_list``
  718. The ``invalid_choice`` error message may contain ``%(value)s``, which will be
  719. replaced with the selected choice.
  720. Takes one extra required argument, ``choices``, as for :class:`ChoiceField`.
  721. ``NullBooleanField``
  722. --------------------
  723. .. class:: NullBooleanField(**kwargs)
  724. * Default widget: :class:`NullBooleanSelect`
  725. * Empty value: ``None``
  726. * Normalizes to: A Python ``True``, ``False`` or ``None`` value.
  727. * Validates nothing (i.e., it never raises a ``ValidationError``).
  728. ``NullBooleanField`` may be used with widgets such as
  729. :class:`~django.forms.Select` or :class:`~django.forms.RadioSelect`
  730. by providing the widget ``choices``::
  731. NullBooleanField(
  732. widget=Select(
  733. choices=[
  734. ("", "Unknown"),
  735. (True, "Yes"),
  736. (False, "No"),
  737. ]
  738. )
  739. )
  740. ``RegexField``
  741. --------------
  742. .. class:: RegexField(**kwargs)
  743. * Default widget: :class:`TextInput`
  744. * Empty value: Whatever you've given as ``empty_value``.
  745. * Normalizes to: A string.
  746. * Uses :class:`~django.core.validators.RegexValidator` to validate that
  747. the given value matches a certain regular expression.
  748. * Error message keys: ``required``, ``invalid``
  749. Takes one required argument:
  750. .. attribute:: regex
  751. A regular expression specified either as a string or a compiled regular
  752. expression object.
  753. Also takes ``max_length``, ``min_length``, ``strip``, and ``empty_value``
  754. which work just as they do for :class:`CharField`.
  755. .. attribute:: strip
  756. Defaults to ``False``. If enabled, stripping will be applied before the
  757. regex validation.
  758. ``SlugField``
  759. -------------
  760. .. class:: SlugField(**kwargs)
  761. * Default widget: :class:`TextInput`
  762. * Empty value: Whatever you've given as :attr:`empty_value`.
  763. * Normalizes to: A string.
  764. * Uses :class:`~django.core.validators.validate_slug` or
  765. :class:`~django.core.validators.validate_unicode_slug` to validate that
  766. the given value contains only letters, numbers, underscores, and hyphens.
  767. * Error messages: ``required``, ``invalid``
  768. This field is intended for use in representing a model
  769. :class:`~django.db.models.SlugField` in forms.
  770. Takes two optional parameters:
  771. .. attribute:: allow_unicode
  772. A boolean instructing the field to accept Unicode letters in addition
  773. to ASCII letters. Defaults to ``False``.
  774. .. attribute:: empty_value
  775. The value to use to represent "empty". Defaults to an empty string.
  776. ``TimeField``
  777. -------------
  778. .. class:: TimeField(**kwargs)
  779. * Default widget: :class:`TimeInput`
  780. * Empty value: ``None``
  781. * Normalizes to: A Python ``datetime.time`` object.
  782. * Validates that the given value is either a ``datetime.time`` or string
  783. formatted in a particular time format.
  784. * Error message keys: ``required``, ``invalid``
  785. Takes one optional argument:
  786. .. attribute:: input_formats
  787. An iterable of formats used to attempt to convert a string to a valid
  788. ``datetime.time`` object.
  789. If no ``input_formats`` argument is provided, the default input formats are
  790. taken from the active locale format ``TIME_INPUT_FORMATS`` key, or from
  791. :setting:`TIME_INPUT_FORMATS` if localization is disabled. See also
  792. :doc:`format localization </topics/i18n/formatting>`.
  793. ``TypedChoiceField``
  794. --------------------
  795. .. class:: TypedChoiceField(**kwargs)
  796. Just like a :class:`ChoiceField`, except :class:`TypedChoiceField` takes two
  797. extra arguments, :attr:`coerce` and :attr:`empty_value`.
  798. * Default widget: :class:`Select`
  799. * Empty value: Whatever you've given as :attr:`empty_value`.
  800. * Normalizes to: A value of the type provided by the :attr:`coerce`
  801. argument.
  802. * Validates that the given value exists in the list of choices and can be
  803. coerced.
  804. * Error message keys: ``required``, ``invalid_choice``
  805. Takes extra arguments:
  806. .. attribute:: coerce
  807. A function that takes one argument and returns a coerced value. Examples
  808. include the built-in ``int``, ``float``, ``bool`` and other types. Defaults
  809. to an identity function. Note that coercion happens after input
  810. validation, so it is possible to coerce to a value not present in
  811. ``choices``.
  812. .. attribute:: empty_value
  813. The value to use to represent "empty." Defaults to the empty string;
  814. ``None`` is another common choice here. Note that this value will not be
  815. coerced by the function given in the ``coerce`` argument, so choose it
  816. accordingly.
  817. ``TypedMultipleChoiceField``
  818. ----------------------------
  819. .. class:: TypedMultipleChoiceField(**kwargs)
  820. Just like a :class:`MultipleChoiceField`, except :class:`TypedMultipleChoiceField`
  821. takes two extra arguments, ``coerce`` and ``empty_value``.
  822. * Default widget: :class:`SelectMultiple`
  823. * Empty value: Whatever you've given as ``empty_value``
  824. * Normalizes to: A list of values of the type provided by the ``coerce``
  825. argument.
  826. * Validates that the given values exists in the list of choices and can be
  827. coerced.
  828. * Error message keys: ``required``, ``invalid_choice``
  829. The ``invalid_choice`` error message may contain ``%(value)s``, which will be
  830. replaced with the selected choice.
  831. Takes two extra arguments, ``coerce`` and ``empty_value``, as for
  832. :class:`TypedChoiceField`.
  833. ``URLField``
  834. ------------
  835. .. class:: URLField(**kwargs)
  836. * Default widget: :class:`URLInput`
  837. * Empty value: Whatever you've given as ``empty_value``.
  838. * Normalizes to: A string.
  839. * Uses :class:`~django.core.validators.URLValidator` to validate that the
  840. given value is a valid URL.
  841. * Error message keys: ``required``, ``invalid``
  842. Has the optional arguments ``max_length``, ``min_length``, ``empty_value``
  843. which work just as they do for :class:`CharField`, and one more argument:
  844. .. attribute:: assume_scheme
  845. The scheme assumed for URLs provided without one. Defaults to
  846. ``"http"``. For example, if ``assume_scheme`` is ``"https"`` and the
  847. provided value is ``"example.com"``, the normalized value will be
  848. ``"https://example.com"``.
  849. .. deprecated:: 5.0
  850. The default value for ``assume_scheme`` will change from ``"http"`` to
  851. ``"https"`` in Django 6.0. Set :setting:`FORMS_URLFIELD_ASSUME_HTTPS`
  852. transitional setting to ``True`` to opt into using ``"https"`` during
  853. the Django 5.x release cycle.
  854. ``UUIDField``
  855. -------------
  856. .. class:: UUIDField(**kwargs)
  857. * Default widget: :class:`TextInput`
  858. * Empty value: ``None``
  859. * Normalizes to: A :class:`~python:uuid.UUID` object.
  860. * Error message keys: ``required``, ``invalid``
  861. This field will accept any string format accepted as the ``hex`` argument
  862. to the :class:`~python:uuid.UUID` constructor.
  863. Slightly complex built-in ``Field`` classes
  864. ===========================================
  865. ``ComboField``
  866. --------------
  867. .. class:: ComboField(**kwargs)
  868. * Default widget: :class:`TextInput`
  869. * Empty value: ``''`` (an empty string)
  870. * Normalizes to: A string.
  871. * Validates the given value against each of the fields specified
  872. as an argument to the ``ComboField``.
  873. * Error message keys: ``required``, ``invalid``
  874. Takes one extra required argument:
  875. .. attribute:: fields
  876. The list of fields that should be used to validate the field's value (in
  877. the order in which they are provided).
  878. .. code-block:: pycon
  879. >>> from django.forms import ComboField
  880. >>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
  881. >>> f.clean("test@example.com")
  882. 'test@example.com'
  883. >>> f.clean("longemailaddress@example.com")
  884. Traceback (most recent call last):
  885. ...
  886. ValidationError: ['Ensure this value has at most 20 characters (it has 28).']
  887. ``MultiValueField``
  888. -------------------
  889. .. class:: MultiValueField(fields=(), **kwargs)
  890. * Default widget: :class:`TextInput`
  891. * Empty value: ``''`` (an empty string)
  892. * Normalizes to: the type returned by the ``compress`` method of the subclass.
  893. * Validates the given value against each of the fields specified
  894. as an argument to the ``MultiValueField``.
  895. * Error message keys: ``required``, ``invalid``, ``incomplete``
  896. Aggregates the logic of multiple fields that together produce a single
  897. value.
  898. This field is abstract and must be subclassed. In contrast with the
  899. single-value fields, subclasses of :class:`MultiValueField` must not
  900. implement :meth:`~django.forms.Field.clean` but instead - implement
  901. :meth:`~MultiValueField.compress`.
  902. Takes one extra required argument:
  903. .. attribute:: fields
  904. A tuple of fields whose values are cleaned and subsequently combined
  905. into a single value. Each value of the field is cleaned by the
  906. corresponding field in ``fields`` -- the first value is cleaned by the
  907. first field, the second value is cleaned by the second field, etc.
  908. Once all fields are cleaned, the list of clean values is combined into
  909. a single value by :meth:`~MultiValueField.compress`.
  910. Also takes some optional arguments:
  911. .. attribute:: require_all_fields
  912. Defaults to ``True``, in which case a ``required`` validation error
  913. will be raised if no value is supplied for any field.
  914. When set to ``False``, the :attr:`Field.required` attribute can be set
  915. to ``False`` for individual fields to make them optional. If no value
  916. is supplied for a required field, an ``incomplete`` validation error
  917. will be raised.
  918. A default ``incomplete`` error message can be defined on the
  919. :class:`MultiValueField` subclass, or different messages can be defined
  920. on each individual field. For example::
  921. from django.core.validators import RegexValidator
  922. class PhoneField(MultiValueField):
  923. def __init__(self, **kwargs):
  924. # Define one message for all fields.
  925. error_messages = {
  926. "incomplete": "Enter a country calling code and a phone number.",
  927. }
  928. # Or define a different message for each field.
  929. fields = (
  930. CharField(
  931. error_messages={"incomplete": "Enter a country calling code."},
  932. validators=[
  933. RegexValidator(r"^[0-9]+$", "Enter a valid country calling code."),
  934. ],
  935. ),
  936. CharField(
  937. error_messages={"incomplete": "Enter a phone number."},
  938. validators=[RegexValidator(r"^[0-9]+$", "Enter a valid phone number.")],
  939. ),
  940. CharField(
  941. validators=[RegexValidator(r"^[0-9]+$", "Enter a valid extension.")],
  942. required=False,
  943. ),
  944. )
  945. super().__init__(
  946. error_messages=error_messages,
  947. fields=fields,
  948. require_all_fields=False,
  949. **kwargs
  950. )
  951. .. attribute:: MultiValueField.widget
  952. Must be a subclass of :class:`django.forms.MultiWidget`.
  953. Default value is :class:`~django.forms.TextInput`, which
  954. probably is not very useful in this case.
  955. .. method:: compress(data_list)
  956. Takes a list of valid values and returns a "compressed" version of
  957. those values -- in a single value. For example,
  958. :class:`SplitDateTimeField` is a subclass which combines a time field
  959. and a date field into a ``datetime`` object.
  960. This method must be implemented in the subclasses.
  961. ``SplitDateTimeField``
  962. ----------------------
  963. .. class:: SplitDateTimeField(**kwargs)
  964. * Default widget: :class:`SplitDateTimeWidget`
  965. * Empty value: ``None``
  966. * Normalizes to: A Python ``datetime.datetime`` object.
  967. * Validates that the given value is a ``datetime.datetime`` or string
  968. formatted in a particular datetime format.
  969. * Error message keys: ``required``, ``invalid``, ``invalid_date``,
  970. ``invalid_time``
  971. Takes two optional arguments:
  972. .. attribute:: input_date_formats
  973. A list of formats used to attempt to convert a string to a valid
  974. ``datetime.date`` object.
  975. If no ``input_date_formats`` argument is provided, the default input formats
  976. for :class:`DateField` are used.
  977. .. attribute:: input_time_formats
  978. A list of formats used to attempt to convert a string to a valid
  979. ``datetime.time`` object.
  980. If no ``input_time_formats`` argument is provided, the default input formats
  981. for :class:`TimeField` are used.
  982. .. _fields-which-handle-relationships:
  983. Fields which handle relationships
  984. =================================
  985. Two fields are available for representing relationships between
  986. models: :class:`ModelChoiceField` and
  987. :class:`ModelMultipleChoiceField`. Both of these fields require a
  988. single ``queryset`` parameter that is used to create the choices for
  989. the field. Upon form validation, these fields will place either one
  990. model object (in the case of ``ModelChoiceField``) or multiple model
  991. objects (in the case of ``ModelMultipleChoiceField``) into the
  992. ``cleaned_data`` dictionary of the form.
  993. For more complex uses, you can specify ``queryset=None`` when declaring the
  994. form field and then populate the ``queryset`` in the form's ``__init__()``
  995. method::
  996. class FooMultipleChoiceForm(forms.Form):
  997. foo_select = forms.ModelMultipleChoiceField(queryset=None)
  998. def __init__(self, *args, **kwargs):
  999. super().__init__(*args, **kwargs)
  1000. self.fields["foo_select"].queryset = ...
  1001. Both ``ModelChoiceField`` and ``ModelMultipleChoiceField`` have an ``iterator``
  1002. attribute which specifies the class used to iterate over the queryset when
  1003. generating choices. See :ref:`iterating-relationship-choices` for details.
  1004. ``ModelChoiceField``
  1005. --------------------
  1006. .. class:: ModelChoiceField(**kwargs)
  1007. * Default widget: :class:`Select`
  1008. * Empty value: ``None``
  1009. * Normalizes to: A model instance.
  1010. * Validates that the given id exists in the queryset.
  1011. * Error message keys: ``required``, ``invalid_choice``
  1012. The ``invalid_choice`` error message may contain ``%(value)s``, which will
  1013. be replaced with the selected choice.
  1014. Allows the selection of a single model object, suitable for representing a
  1015. foreign key. Note that the default widget for ``ModelChoiceField`` becomes
  1016. impractical when the number of entries increases. You should avoid using it
  1017. for more than 100 items.
  1018. A single argument is required:
  1019. .. attribute:: queryset
  1020. A ``QuerySet`` of model objects from which the choices for the field
  1021. are derived and which is used to validate the user's selection. It's
  1022. evaluated when the form is rendered.
  1023. ``ModelChoiceField`` also takes several optional arguments:
  1024. .. attribute:: empty_label
  1025. By default the ``<select>`` widget used by ``ModelChoiceField`` will have an
  1026. empty choice at the top of the list. You can change the text of this
  1027. label (which is ``"---------"`` by default) with the ``empty_label``
  1028. attribute, or you can disable the empty label entirely by setting
  1029. ``empty_label`` to ``None``::
  1030. # A custom empty label
  1031. field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)")
  1032. # No empty label
  1033. field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
  1034. Note that no empty choice is created (regardless of the value of
  1035. ``empty_label``) if a ``ModelChoiceField`` is required and has a
  1036. default initial value, or a ``widget`` is set to
  1037. :class:`~django.forms.RadioSelect` and the
  1038. :attr:`~ModelChoiceField.blank` argument is ``False``.
  1039. .. attribute:: to_field_name
  1040. This optional argument is used to specify the field to use as the value
  1041. of the choices in the field's widget. Be sure it's a unique field for
  1042. the model, otherwise the selected value could match more than one
  1043. object. By default it is set to ``None``, in which case the primary key
  1044. of each object will be used. For example::
  1045. # No custom to_field_name
  1046. field1 = forms.ModelChoiceField(queryset=...)
  1047. would yield:
  1048. .. code-block:: html
  1049. <select id="id_field1" name="field1">
  1050. <option value="obj1.pk">Object1</option>
  1051. <option value="obj2.pk">Object2</option>
  1052. ...
  1053. </select>
  1054. and::
  1055. # to_field_name provided
  1056. field2 = forms.ModelChoiceField(queryset=..., to_field_name="name")
  1057. would yield:
  1058. .. code-block:: html
  1059. <select id="id_field2" name="field2">
  1060. <option value="obj1.name">Object1</option>
  1061. <option value="obj2.name">Object2</option>
  1062. ...
  1063. </select>
  1064. .. attribute:: blank
  1065. When using the :class:`~django.forms.RadioSelect` widget, this optional
  1066. boolean argument determines whether an empty choice is created. By
  1067. default, ``blank`` is ``False``, in which case no empty choice is
  1068. created.
  1069. ``ModelChoiceField`` also has the attribute:
  1070. .. attribute:: iterator
  1071. The iterator class used to generate field choices from ``queryset``. By
  1072. default, :class:`ModelChoiceIterator`.
  1073. The ``__str__()`` method of the model will be called to generate string
  1074. representations of the objects for use in the field's choices. To provide
  1075. customized representations, subclass ``ModelChoiceField`` and override
  1076. ``label_from_instance``. This method will receive a model object and should
  1077. return a string suitable for representing it. For example::
  1078. from django.forms import ModelChoiceField
  1079. class MyModelChoiceField(ModelChoiceField):
  1080. def label_from_instance(self, obj):
  1081. return "My Object #%i" % obj.id
  1082. ``ModelMultipleChoiceField``
  1083. ----------------------------
  1084. .. class:: ModelMultipleChoiceField(**kwargs)
  1085. * Default widget: :class:`SelectMultiple`
  1086. * Empty value: An empty ``QuerySet`` (``self.queryset.none()``)
  1087. * Normalizes to: A ``QuerySet`` of model instances.
  1088. * Validates that every id in the given list of values exists in the
  1089. queryset.
  1090. * Error message keys: ``required``, ``invalid_list``, ``invalid_choice``,
  1091. ``invalid_pk_value``
  1092. The ``invalid_choice`` message may contain ``%(value)s`` and the
  1093. ``invalid_pk_value`` message may contain ``%(pk)s``, which will be
  1094. substituted by the appropriate values.
  1095. Allows the selection of one or more model objects, suitable for
  1096. representing a many-to-many relation. As with :class:`ModelChoiceField`,
  1097. you can use ``label_from_instance`` to customize the object
  1098. representations.
  1099. A single argument is required:
  1100. .. attribute:: queryset
  1101. Same as :class:`ModelChoiceField.queryset`.
  1102. Takes one optional argument:
  1103. .. attribute:: to_field_name
  1104. Same as :class:`ModelChoiceField.to_field_name`.
  1105. ``ModelMultipleChoiceField`` also has the attribute:
  1106. .. attribute:: iterator
  1107. Same as :class:`ModelChoiceField.iterator`.
  1108. .. _iterating-relationship-choices:
  1109. Iterating relationship choices
  1110. ------------------------------
  1111. By default, :class:`ModelChoiceField` and :class:`ModelMultipleChoiceField` use
  1112. :class:`ModelChoiceIterator` to generate their field ``choices``.
  1113. When iterated, ``ModelChoiceIterator`` yields 2-tuple choices containing
  1114. :class:`ModelChoiceIteratorValue` instances as the first ``value`` element in
  1115. each choice. ``ModelChoiceIteratorValue`` wraps the choice value while
  1116. maintaining a reference to the source model instance that can be used in custom
  1117. widget implementations, for example, to add `data-* attributes`_ to
  1118. ``<option>`` elements.
  1119. .. _`data-* attributes`: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*
  1120. For example, consider the following models::
  1121. from django.db import models
  1122. class Topping(models.Model):
  1123. name = models.CharField(max_length=100)
  1124. price = models.DecimalField(decimal_places=2, max_digits=6)
  1125. def __str__(self):
  1126. return self.name
  1127. class Pizza(models.Model):
  1128. topping = models.ForeignKey(Topping, on_delete=models.CASCADE)
  1129. You can use a :class:`~django.forms.Select` widget subclass to include
  1130. the value of ``Topping.price`` as the HTML attribute ``data-price`` for each
  1131. ``<option>`` element::
  1132. from django import forms
  1133. class ToppingSelect(forms.Select):
  1134. def create_option(
  1135. self, name, value, label, selected, index, subindex=None, attrs=None
  1136. ):
  1137. option = super().create_option(
  1138. name, value, label, selected, index, subindex, attrs
  1139. )
  1140. if value:
  1141. option["attrs"]["data-price"] = value.instance.price
  1142. return option
  1143. class PizzaForm(forms.ModelForm):
  1144. class Meta:
  1145. model = Pizza
  1146. fields = ["topping"]
  1147. widgets = {"topping": ToppingSelect}
  1148. This will render the ``Pizza.topping`` select as:
  1149. .. code-block:: html
  1150. <select id="id_topping" name="topping" required>
  1151. <option value="" selected>---------</option>
  1152. <option value="1" data-price="1.50">mushrooms</option>
  1153. <option value="2" data-price="1.25">onions</option>
  1154. <option value="3" data-price="1.75">peppers</option>
  1155. <option value="4" data-price="2.00">pineapple</option>
  1156. </select>
  1157. For more advanced usage you may subclass ``ModelChoiceIterator`` in order to
  1158. customize the yielded 2-tuple choices.
  1159. ``ModelChoiceIterator``
  1160. ~~~~~~~~~~~~~~~~~~~~~~~
  1161. .. class:: ModelChoiceIterator(field)
  1162. The default class assigned to the ``iterator`` attribute of
  1163. :class:`ModelChoiceField` and :class:`ModelMultipleChoiceField`. An
  1164. iterable that yields 2-tuple choices from the queryset.
  1165. A single argument is required:
  1166. .. attribute:: field
  1167. The instance of ``ModelChoiceField`` or ``ModelMultipleChoiceField`` to
  1168. iterate and yield choices.
  1169. ``ModelChoiceIterator`` has the following method:
  1170. .. method:: __iter__()
  1171. Yields 2-tuple choices, in the ``(value, label)`` format used by
  1172. :attr:`ChoiceField.choices`. The first ``value`` element is a
  1173. :class:`ModelChoiceIteratorValue` instance.
  1174. ``ModelChoiceIteratorValue``
  1175. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1176. .. class:: ModelChoiceIteratorValue(value, instance)
  1177. Two arguments are required:
  1178. .. attribute:: value
  1179. The value of the choice. This value is used to render the ``value``
  1180. attribute of an HTML ``<option>`` element.
  1181. .. attribute:: instance
  1182. The model instance from the queryset. The instance can be accessed in
  1183. custom ``ChoiceWidget.create_option()`` implementations to adjust the
  1184. rendered HTML.
  1185. ``ModelChoiceIteratorValue`` has the following method:
  1186. .. method:: __str__()
  1187. Return ``value`` as a string to be rendered in HTML.
  1188. Creating custom fields
  1189. ======================
  1190. If the built-in ``Field`` classes don't meet your needs, you can create custom
  1191. ``Field`` classes. To do this, create a subclass of ``django.forms.Field``. Its
  1192. only requirements are that it implement a ``clean()`` method and that its
  1193. ``__init__()`` method accept the core arguments mentioned above (``required``,
  1194. ``label``, ``initial``, ``widget``, ``help_text``).
  1195. You can also customize how a field will be accessed by overriding
  1196. :meth:`~django.forms.Field.get_bound_field()`.