fields.txt 57 KB

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