fields.txt 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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 ``django.forms.ValidationError``
  16. exception or returns the clean value::
  17. >>> from django import forms
  18. >>> f = forms.EmailField()
  19. >>> f.clean('foo@example.com')
  20. 'foo@example.com'
  21. >>> f.clean('invalid email address')
  22. Traceback (most recent call last):
  23. ...
  24. ValidationError: ['Enter a valid email address.']
  25. .. _core-field-arguments:
  26. Core field arguments
  27. ====================
  28. Each ``Field`` class constructor takes at least these arguments. Some
  29. ``Field`` classes take additional, field-specific arguments, but the following
  30. should *always* be accepted:
  31. ``required``
  32. ------------
  33. .. attribute:: Field.required
  34. By default, each ``Field`` class assumes the value is required, so if you pass
  35. an empty value -- either ``None`` or the empty string (``""``) -- then
  36. ``clean()`` will raise a ``ValidationError`` exception::
  37. >>> from django import forms
  38. >>> f = forms.CharField()
  39. >>> f.clean('foo')
  40. 'foo'
  41. >>> f.clean('')
  42. Traceback (most recent call last):
  43. ...
  44. ValidationError: ['This field is required.']
  45. >>> f.clean(None)
  46. Traceback (most recent call last):
  47. ...
  48. ValidationError: ['This field is required.']
  49. >>> f.clean(' ')
  50. ' '
  51. >>> f.clean(0)
  52. '0'
  53. >>> f.clean(True)
  54. 'True'
  55. >>> f.clean(False)
  56. 'False'
  57. To specify that a field is *not* required, pass ``required=False`` to the
  58. ``Field`` constructor::
  59. >>> f = forms.CharField(required=False)
  60. >>> f.clean('foo')
  61. 'foo'
  62. >>> f.clean('')
  63. ''
  64. >>> f.clean(None)
  65. ''
  66. >>> f.clean(0)
  67. '0'
  68. >>> f.clean(True)
  69. 'True'
  70. >>> f.clean(False)
  71. 'False'
  72. If a ``Field`` has ``required=False`` and you pass ``clean()`` an empty value,
  73. then ``clean()`` will return a *normalized* empty value rather than raising
  74. ``ValidationError``. For ``CharField``, this will be a Unicode empty string.
  75. For other ``Field`` classes, it might be ``None``. (This varies from field to
  76. field.)
  77. Widgets of required form fields have the ``required`` HTML attribute. Set the
  78. :attr:`Form.use_required_attribute` attribute to ``False`` to disable it. The
  79. ``required`` attribute isn't included on forms of formsets because the browser
  80. validation may not be correct when adding and deleting formsets.
  81. .. versionadded:: 1.10
  82. Support for the ``required`` HTML attribute was added.
  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 "Outputting forms as HTML" above, 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. >>> from django import forms
  95. >>> class CommentForm(forms.Form):
  96. ... name = forms.CharField(label='Your name')
  97. ... url = forms.URLField(label='Your website', required=False)
  98. ... comment = forms.CharField()
  99. >>> f = CommentForm(auto_id=False)
  100. >>> print(f)
  101. <tr><th>Your name:</th><td><input type="text" name="name" required /></td></tr>
  102. <tr><th>Your website:</th><td><input type="url" name="url" required /></td></tr>
  103. <tr><th>Comment:</th><td><input type="text" name="comment" required /></td></tr>
  104. ``label_suffix``
  105. ----------------
  106. .. attribute:: Field.label_suffix
  107. The ``label_suffix`` argument lets you override the form's
  108. :attr:`~django.forms.Form.label_suffix` on a per-field basis::
  109. >>> class ContactForm(forms.Form):
  110. ... age = forms.IntegerField()
  111. ... nationality = forms.CharField()
  112. ... captcha_answer = forms.IntegerField(label='2 + 2', label_suffix=' =')
  113. >>> f = ContactForm(label_suffix='?')
  114. >>> print(f.as_p())
  115. <p><label for="id_age">Age?</label> <input id="id_age" name="age" type="number" required /></p>
  116. <p><label for="id_nationality">Nationality?</label> <input id="id_nationality" name="nationality" type="text" required /></p>
  117. <p><label for="id_captcha_answer">2 + 2 =</label> <input id="id_captcha_answer" name="captcha_answer" type="number" required /></p>
  118. ``initial``
  119. -----------
  120. .. attribute:: Field.initial
  121. The ``initial`` argument lets you specify the initial value to use when
  122. rendering this ``Field`` in an unbound ``Form``.
  123. To specify dynamic initial data, see the :attr:`Form.initial` parameter.
  124. The use-case for this is when you want to display an "empty" form in which a
  125. field is initialized to a particular value. For example::
  126. >>> from django import forms
  127. >>> class CommentForm(forms.Form):
  128. ... name = forms.CharField(initial='Your name')
  129. ... url = forms.URLField(initial='http://')
  130. ... comment = forms.CharField()
  131. >>> f = CommentForm(auto_id=False)
  132. >>> print(f)
  133. <tr><th>Name:</th><td><input type="text" name="name" value="Your name" required /></td></tr>
  134. <tr><th>Url:</th><td><input type="url" name="url" value="http://" required /></td></tr>
  135. <tr><th>Comment:</th><td><input type="text" name="comment" required /></td></tr>
  136. You may be thinking, why not just pass a dictionary of the initial values as
  137. data when displaying the form? Well, if you do that, you'll trigger validation,
  138. and the HTML output will include any validation errors::
  139. >>> class CommentForm(forms.Form):
  140. ... name = forms.CharField()
  141. ... url = forms.URLField()
  142. ... comment = forms.CharField()
  143. >>> default_data = {'name': 'Your name', 'url': 'http://'}
  144. >>> f = CommentForm(default_data, auto_id=False)
  145. >>> print(f)
  146. <tr><th>Name:</th><td><input type="text" name="name" value="Your name" required /></td></tr>
  147. <tr><th>Url:</th><td><ul class="errorlist"><li>Enter a valid URL.</li></ul><input type="url" name="url" value="http://" required /></td></tr>
  148. <tr><th>Comment:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="comment" required /></td></tr>
  149. This is why ``initial`` values are only displayed for unbound forms. For bound
  150. forms, the HTML output will use the bound data.
  151. Also note that ``initial`` values are *not* used as "fallback" data in
  152. validation if a particular field's value is not given. ``initial`` values are
  153. *only* intended for initial form display::
  154. >>> class CommentForm(forms.Form):
  155. ... name = forms.CharField(initial='Your name')
  156. ... url = forms.URLField(initial='http://')
  157. ... comment = forms.CharField()
  158. >>> data = {'name': '', 'url': '', 'comment': 'Foo'}
  159. >>> f = CommentForm(data)
  160. >>> f.is_valid()
  161. False
  162. # The form does *not* fall back to using the initial values.
  163. >>> f.errors
  164. {'url': ['This field is required.'], 'name': ['This field is required.']}
  165. Instead of a constant, you can also pass any callable::
  166. >>> import datetime
  167. >>> class DateForm(forms.Form):
  168. ... day = forms.DateField(initial=datetime.date.today)
  169. >>> print(DateForm())
  170. <tr><th>Day:</th><td><input type="text" name="day" value="12/23/2008" required /><td></tr>
  171. The callable will be evaluated only when the unbound form is displayed, not when it is defined.
  172. ``widget``
  173. ----------
  174. .. attribute:: Field.widget
  175. The ``widget`` argument lets you specify a ``Widget`` class to use when
  176. rendering this ``Field``. See :doc:`/ref/forms/widgets` for more information.
  177. ``help_text``
  178. -------------
  179. .. attribute:: Field.help_text
  180. The ``help_text`` argument lets you specify descriptive text for this
  181. ``Field``. If you provide ``help_text``, it will be displayed next to the
  182. ``Field`` when the ``Field`` is rendered by one of the convenience ``Form``
  183. methods (e.g., ``as_ul()``).
  184. Like the model field's :attr:`~django.db.models.Field.help_text`, this value
  185. isn't HTML-escaped in automatically-generated forms.
  186. Here's a full example ``Form`` that implements ``help_text`` for two of its
  187. fields. We've specified ``auto_id=False`` to simplify the output::
  188. >>> from django import forms
  189. >>> class HelpTextContactForm(forms.Form):
  190. ... subject = forms.CharField(max_length=100, help_text='100 characters max.')
  191. ... message = forms.CharField()
  192. ... sender = forms.EmailField(help_text='A valid email address, please.')
  193. ... cc_myself = forms.BooleanField(required=False)
  194. >>> f = HelpTextContactForm(auto_id=False)
  195. >>> print(f.as_table())
  196. <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" required /><br /><span class="helptext">100 characters max.</span></td></tr>
  197. <tr><th>Message:</th><td><input type="text" name="message" required /></td></tr>
  198. <tr><th>Sender:</th><td><input type="email" name="sender" required /><br />A valid email address, please.</td></tr>
  199. <tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr>
  200. >>> print(f.as_ul()))
  201. <li>Subject: <input type="text" name="subject" maxlength="100" required /> <span class="helptext">100 characters max.</span></li>
  202. <li>Message: <input type="text" name="message" required /></li>
  203. <li>Sender: <input type="email" name="sender" required /> A valid email address, please.</li>
  204. <li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
  205. >>> print(f.as_p())
  206. <p>Subject: <input type="text" name="subject" maxlength="100" required /> <span class="helptext">100 characters max.</span></p>
  207. <p>Message: <input type="text" name="message" required /></p>
  208. <p>Sender: <input type="email" name="sender" required /> A valid email address, please.</p>
  209. <p>Cc myself: <input type="checkbox" name="cc_myself" /></p>
  210. ``error_messages``
  211. ------------------
  212. .. attribute:: Field.error_messages
  213. The ``error_messages`` argument lets you override the default messages that the
  214. field will raise. Pass in a dictionary with keys matching the error messages you
  215. want to override. For example, here is the default error message::
  216. >>> from django import forms
  217. >>> generic = forms.CharField()
  218. >>> generic.clean('')
  219. Traceback (most recent call last):
  220. ...
  221. ValidationError: ['This field is required.']
  222. And here is a custom error message::
  223. >>> name = forms.CharField(error_messages={'required': 'Please enter your name'})
  224. >>> name.clean('')
  225. Traceback (most recent call last):
  226. ...
  227. ValidationError: ['Please enter your name']
  228. In the `built-in Field classes`_ section below, each ``Field`` defines the
  229. error message keys it uses.
  230. ``validators``
  231. --------------
  232. .. attribute:: Field.validators
  233. The ``validators`` argument lets you provide a list of validation functions
  234. for this field.
  235. See the :doc:`validators documentation </ref/validators>` for more information.
  236. ``localize``
  237. ------------
  238. .. attribute:: Field.localize
  239. The ``localize`` argument enables the localization of form data input, as well
  240. as the rendered output.
  241. See the :doc:`format localization </topics/i18n/formatting>` documentation for
  242. more information.
  243. ``disabled``
  244. ------------
  245. .. attribute:: Field.disabled
  246. The ``disabled`` boolean argument, when set to ``True``, disables a form field
  247. using the ``disabled`` HTML attribute so that it won't be editable by users.
  248. Even if a user tampers with the field's value submitted to the server, it will
  249. be ignored in favor of the value from the form's initial data.
  250. Checking if the field data has changed
  251. ======================================
  252. ``has_changed()``
  253. -----------------
  254. .. method:: Field.has_changed()
  255. The ``has_changed()`` method is used to determine if the field value has changed
  256. from the initial value. Returns ``True`` or ``False``.
  257. See the :class:`Form.has_changed()` documentation for more information.
  258. .. _built-in-fields:
  259. Built-in ``Field`` classes
  260. ==========================
  261. Naturally, the ``forms`` library comes with a set of ``Field`` classes that
  262. represent common validation needs. This section documents each built-in field.
  263. For each field, we describe the default widget used if you don't specify
  264. ``widget``. We also specify the value returned when you provide an empty value
  265. (see the section on ``required`` above to understand what that means).
  266. ``BooleanField``
  267. ----------------
  268. .. class:: BooleanField(**kwargs)
  269. * Default widget: :class:`CheckboxInput`
  270. * Empty value: ``False``
  271. * Normalizes to: A Python ``True`` or ``False`` value.
  272. * Validates that the value is ``True`` (e.g. the check box is checked) if
  273. the field has ``required=True``.
  274. * Error message keys: ``required``
  275. .. note::
  276. Since all ``Field`` subclasses have ``required=True`` by default, the
  277. validation condition here is important. If you want to include a boolean
  278. in your form that can be either ``True`` or ``False`` (e.g. a checked or
  279. unchecked checkbox), you must remember to pass in ``required=False`` when
  280. creating the ``BooleanField``.
  281. ``CharField``
  282. -------------
  283. .. class:: CharField(**kwargs)
  284. * Default widget: :class:`TextInput`
  285. * Empty value: Whatever you've given as :attr:`empty_value`.
  286. * Normalizes to: A Unicode object.
  287. * Validates ``max_length`` or ``min_length``, if they are provided.
  288. Otherwise, all inputs are valid.
  289. * Error message keys: ``required``, ``max_length``, ``min_length``
  290. Has three optional arguments for validation:
  291. .. attribute:: max_length
  292. .. attribute:: min_length
  293. If provided, these arguments ensure that the string is at most or at least
  294. the given length.
  295. .. attribute:: strip
  296. If ``True`` (default), the value will be stripped of leading and
  297. trailing whitespace.
  298. .. attribute:: empty_value
  299. .. versionadded:: 1.11
  300. The value to use to represent "empty". Defaults to an empty string.
  301. ``ChoiceField``
  302. ---------------
  303. .. class:: ChoiceField(**kwargs)
  304. * Default widget: :class:`Select`
  305. * Empty value: ``''`` (an empty string)
  306. * Normalizes to: A Unicode object.
  307. * Validates that the given value exists in the list of choices.
  308. * Error message keys: ``required``, ``invalid_choice``
  309. The ``invalid_choice`` error message may contain ``%(value)s``, which will be
  310. replaced with the selected choice.
  311. Takes one extra required argument:
  312. .. attribute:: choices
  313. Either an iterable (e.g., a list or tuple) of 2-tuples to use as
  314. choices for this field, or a callable that returns such an iterable.
  315. This argument accepts the same formats as the ``choices`` argument to a
  316. model field. See the :ref:`model field reference documentation on
  317. choices <field-choices>` for more details. If the argument is a
  318. callable, it is evaluated each time the field's form is initialized.
  319. ``TypedChoiceField``
  320. --------------------
  321. .. class:: TypedChoiceField(**kwargs)
  322. Just like a :class:`ChoiceField`, except :class:`TypedChoiceField` takes two
  323. extra arguments, :attr:`coerce` and :attr:`empty_value`.
  324. * Default widget: :class:`Select`
  325. * Empty value: Whatever you've given as :attr:`empty_value`.
  326. * Normalizes to: A value of the type provided by the :attr:`coerce`
  327. argument.
  328. * Validates that the given value exists in the list of choices and can be
  329. coerced.
  330. * Error message keys: ``required``, ``invalid_choice``
  331. Takes extra arguments:
  332. .. attribute:: coerce
  333. A function that takes one argument and returns a coerced value. Examples
  334. include the built-in ``int``, ``float``, ``bool`` and other types. Defaults
  335. to an identity function. Note that coercion happens after input
  336. validation, so it is possible to coerce to a value not present in
  337. ``choices``.
  338. .. attribute:: empty_value
  339. The value to use to represent "empty." Defaults to the empty string;
  340. ``None`` is another common choice here. Note that this value will not be
  341. coerced by the function given in the ``coerce`` argument, so choose it
  342. accordingly.
  343. ``DateField``
  344. -------------
  345. .. class:: DateField(**kwargs)
  346. * Default widget: :class:`DateInput`
  347. * Empty value: ``None``
  348. * Normalizes to: A Python ``datetime.date`` object.
  349. * Validates that the given value is either a ``datetime.date``,
  350. ``datetime.datetime`` or string formatted in a particular date format.
  351. * Error message keys: ``required``, ``invalid``
  352. Takes one optional argument:
  353. .. attribute:: input_formats
  354. A list of formats used to attempt to convert a string to a valid
  355. ``datetime.date`` object.
  356. If no ``input_formats`` argument is provided, the default input formats are::
  357. ['%Y-%m-%d', # '2006-10-25'
  358. '%m/%d/%Y', # '10/25/2006'
  359. '%m/%d/%y'] # '10/25/06'
  360. Additionally, if you specify :setting:`USE_L10N=False<USE_L10N>` in your settings, the
  361. following will also be included in the default input formats::
  362. ['%b %d %Y', # 'Oct 25 2006'
  363. '%b %d, %Y', # 'Oct 25, 2006'
  364. '%d %b %Y', # '25 Oct 2006'
  365. '%d %b, %Y', # '25 Oct, 2006'
  366. '%B %d %Y', # 'October 25 2006'
  367. '%B %d, %Y', # 'October 25, 2006'
  368. '%d %B %Y', # '25 October 2006'
  369. '%d %B, %Y'] # '25 October, 2006'
  370. See also :doc:`format localization </topics/i18n/formatting>`.
  371. ``DateTimeField``
  372. -----------------
  373. .. class:: DateTimeField(**kwargs)
  374. * Default widget: :class:`DateTimeInput`
  375. * Empty value: ``None``
  376. * Normalizes to: A Python ``datetime.datetime`` object.
  377. * Validates that the given value is either a ``datetime.datetime``,
  378. ``datetime.date`` or string formatted in a particular datetime format.
  379. * Error message keys: ``required``, ``invalid``
  380. Takes one optional argument:
  381. .. attribute:: input_formats
  382. A list of formats used to attempt to convert a string to a valid
  383. ``datetime.datetime`` object.
  384. If no ``input_formats`` argument is provided, the default input formats are::
  385. ['%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
  386. '%Y-%m-%d %H:%M', # '2006-10-25 14:30'
  387. '%Y-%m-%d', # '2006-10-25'
  388. '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
  389. '%m/%d/%Y %H:%M', # '10/25/2006 14:30'
  390. '%m/%d/%Y', # '10/25/2006'
  391. '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
  392. '%m/%d/%y %H:%M', # '10/25/06 14:30'
  393. '%m/%d/%y'] # '10/25/06'
  394. See also :doc:`format localization </topics/i18n/formatting>`.
  395. ``DecimalField``
  396. ----------------
  397. .. class:: DecimalField(**kwargs)
  398. * Default widget: :class:`NumberInput` when :attr:`Field.localize` is
  399. ``False``, else :class:`TextInput`.
  400. * Empty value: ``None``
  401. * Normalizes to: A Python ``decimal``.
  402. * Validates that the given value is a decimal. Leading and trailing
  403. whitespace is ignored.
  404. * Error message keys: ``required``, ``invalid``, ``max_value``,
  405. ``min_value``, ``max_digits``, ``max_decimal_places``,
  406. ``max_whole_digits``
  407. The ``max_value`` and ``min_value`` error messages may contain
  408. ``%(limit_value)s``, which will be substituted by the appropriate limit.
  409. Similarly, the ``max_digits``, ``max_decimal_places`` and
  410. ``max_whole_digits`` error messages may contain ``%(max)s``.
  411. Takes four optional arguments:
  412. .. attribute:: max_value
  413. .. attribute:: min_value
  414. These control the range of values permitted in the field, and should be
  415. given as ``decimal.Decimal`` values.
  416. .. attribute:: max_digits
  417. The maximum number of digits (those before the decimal point plus those
  418. after the decimal point, with leading zeros stripped) permitted in the
  419. value.
  420. .. attribute:: decimal_places
  421. The maximum number of decimal places permitted.
  422. ``DurationField``
  423. -----------------
  424. .. class:: DurationField(**kwargs)
  425. * Default widget: :class:`TextInput`
  426. * Empty value: ``None``
  427. * Normalizes to: A Python :class:`~python:datetime.timedelta`.
  428. * Validates that the given value is a string which can be converted into a
  429. ``timedelta``.
  430. * Error message keys: ``required``, ``invalid``.
  431. Accepts any format understood by
  432. :func:`~django.utils.dateparse.parse_duration`.
  433. ``EmailField``
  434. --------------
  435. .. class:: EmailField(**kwargs)
  436. * Default widget: :class:`EmailInput`
  437. * Empty value: ``''`` (an empty string)
  438. * Normalizes to: A Unicode object.
  439. * Validates that the given value is a valid email address, using a
  440. moderately complex regular expression.
  441. * Error message keys: ``required``, ``invalid``
  442. Has two optional arguments for validation, ``max_length`` and ``min_length``.
  443. If provided, these arguments ensure that the string is at most or at least the
  444. given length.
  445. ``FileField``
  446. -------------
  447. .. class:: FileField(**kwargs)
  448. * Default widget: :class:`ClearableFileInput`
  449. * Empty value: ``None``
  450. * Normalizes to: An ``UploadedFile`` object that wraps the file content
  451. and file name into a single object.
  452. * Can validate that non-empty file data has been bound to the form.
  453. * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,
  454. ``max_length``
  455. Has two optional arguments for validation, ``max_length`` and
  456. ``allow_empty_file``. If provided, these ensure that the file name is at
  457. most the given length, and that validation will succeed even if the file
  458. content is empty.
  459. To learn more about the ``UploadedFile`` object, see the :doc:`file uploads
  460. documentation </topics/http/file-uploads>`.
  461. When you use a ``FileField`` in a form, you must also remember to
  462. :ref:`bind the file data to the form <binding-uploaded-files>`.
  463. The ``max_length`` error refers to the length of the filename. In the error
  464. message for that key, ``%(max)d`` will be replaced with the maximum filename
  465. length and ``%(length)d`` will be replaced with the current filename length.
  466. ``FilePathField``
  467. -----------------
  468. .. class:: FilePathField(**kwargs)
  469. * Default widget: :class:`Select`
  470. * Empty value: ``None``
  471. * Normalizes to: A unicode object
  472. * Validates that the selected choice exists in the list of choices.
  473. * Error message keys: ``required``, ``invalid_choice``
  474. The field allows choosing from files inside a certain directory. It takes five
  475. extra arguments; only ``path`` is required:
  476. .. attribute:: path
  477. The absolute path to the directory whose contents you want listed. This
  478. directory must exist.
  479. .. attribute:: recursive
  480. If ``False`` (the default) only the direct contents of ``path`` will be
  481. offered as choices. If ``True``, the directory will be descended into
  482. recursively and all descendants will be listed as choices.
  483. .. attribute:: match
  484. A regular expression pattern; only files with names matching this expression
  485. will be allowed as choices.
  486. .. attribute:: allow_files
  487. Optional. Either ``True`` or ``False``. Default is ``True``. Specifies
  488. whether files in the specified location should be included. Either this or
  489. :attr:`allow_folders` must be ``True``.
  490. .. attribute:: allow_folders
  491. Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
  492. whether folders in the specified location should be included. Either this or
  493. :attr:`allow_files` must be ``True``.
  494. ``FloatField``
  495. --------------
  496. .. class:: FloatField(**kwargs)
  497. * Default widget: :class:`NumberInput` when :attr:`Field.localize` is
  498. ``False``, else :class:`TextInput`.
  499. * Empty value: ``None``
  500. * Normalizes to: A Python float.
  501. * Validates that the given value is a float. Leading and trailing
  502. whitespace is allowed, as in Python's ``float()`` function.
  503. * Error message keys: ``required``, ``invalid``, ``max_value``,
  504. ``min_value``
  505. Takes two optional arguments for validation, ``max_value`` and ``min_value``.
  506. These control the range of values permitted in the field.
  507. ``ImageField``
  508. --------------
  509. .. class:: ImageField(**kwargs)
  510. * Default widget: :class:`ClearableFileInput`
  511. * Empty value: ``None``
  512. * Normalizes to: An ``UploadedFile`` object that wraps the file content
  513. and file name into a single object.
  514. * Validates that file data has been bound to the form, and that the
  515. file is of an image format understood by Pillow.
  516. * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,
  517. ``invalid_image``
  518. Using an ``ImageField`` requires that `Pillow`_ is installed with support
  519. for the image formats you use. If you encounter a ``corrupt image`` error
  520. when you upload an image, it usually means that Pillow doesn't understand
  521. its format. To fix this, install the appropriate library and reinstall
  522. Pillow.
  523. When you use an ``ImageField`` on a form, you must also remember to
  524. :ref:`bind the file data to the form <binding-uploaded-files>`.
  525. After the field has been cleaned and validated, the ``UploadedFile``
  526. object will have an additional ``image`` attribute containing the Pillow
  527. `Image`_ instance used to check if the file was a valid image. Also,
  528. ``UploadedFile.content_type`` will be updated with the image's content type
  529. if Pillow can determine it, otherwise it will be set to ``None``.
  530. .. _Pillow: https://pillow.readthedocs.io/en/latest/
  531. .. _Image: https://pillow.readthedocs.io/en/latest/reference/Image.html
  532. ``IntegerField``
  533. ----------------
  534. .. class:: IntegerField(**kwargs)
  535. * Default widget: :class:`NumberInput` when :attr:`Field.localize` is
  536. ``False``, else :class:`TextInput`.
  537. * Empty value: ``None``
  538. * Normalizes to: A Python integer.
  539. * Validates that the given value is an integer. Leading and trailing
  540. whitespace is allowed, as in Python's ``int()`` function.
  541. * Error message keys: ``required``, ``invalid``, ``max_value``,
  542. ``min_value``
  543. The ``max_value`` and ``min_value`` error messages may contain
  544. ``%(limit_value)s``, which will be substituted by the appropriate limit.
  545. Takes two optional arguments for validation:
  546. .. attribute:: max_value
  547. .. attribute:: min_value
  548. These control the range of values permitted in the field.
  549. ``GenericIPAddressField``
  550. -------------------------
  551. .. class:: GenericIPAddressField(**kwargs)
  552. A field containing either an IPv4 or an IPv6 address.
  553. * Default widget: :class:`TextInput`
  554. * Empty value: ``''`` (an empty string)
  555. * Normalizes to: A Unicode object. IPv6 addresses are
  556. normalized as described below.
  557. * Validates that the given value is a valid IP address.
  558. * Error message keys: ``required``, ``invalid``
  559. The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2,
  560. including using the IPv4 format suggested in paragraph 3 of that section, like
  561. ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to
  562. ``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters
  563. are converted to lowercase.
  564. Takes two optional arguments:
  565. .. attribute:: protocol
  566. Limits valid inputs to the specified protocol.
  567. Accepted values are ``both`` (default), ``IPv4``
  568. or ``IPv6``. Matching is case insensitive.
  569. .. attribute:: unpack_ipv4
  570. Unpacks IPv4 mapped addresses like ``::ffff:192.0.2.1``.
  571. If this option is enabled that address would be unpacked to
  572. ``192.0.2.1``. Default is disabled. Can only be used
  573. when ``protocol`` is set to ``'both'``.
  574. ``MultipleChoiceField``
  575. -----------------------
  576. .. class:: MultipleChoiceField(**kwargs)
  577. * Default widget: :class:`SelectMultiple`
  578. * Empty value: ``[]`` (an empty list)
  579. * Normalizes to: A list of Unicode objects.
  580. * Validates that every value in the given list of values exists in the list
  581. of choices.
  582. * Error message keys: ``required``, ``invalid_choice``, ``invalid_list``
  583. The ``invalid_choice`` error message may contain ``%(value)s``, which will be
  584. replaced with the selected choice.
  585. Takes one extra required argument, ``choices``, as for :class:`ChoiceField`.
  586. ``TypedMultipleChoiceField``
  587. ----------------------------
  588. .. class:: TypedMultipleChoiceField(**kwargs)
  589. Just like a :class:`MultipleChoiceField`, except :class:`TypedMultipleChoiceField`
  590. takes two extra arguments, ``coerce`` and ``empty_value``.
  591. * Default widget: :class:`SelectMultiple`
  592. * Empty value: Whatever you've given as ``empty_value``
  593. * Normalizes to: A list of values of the type provided by the ``coerce``
  594. argument.
  595. * Validates that the given values exists in the list of choices and can be
  596. coerced.
  597. * Error message keys: ``required``, ``invalid_choice``
  598. The ``invalid_choice`` error message may contain ``%(value)s``, which will be
  599. replaced with the selected choice.
  600. Takes two extra arguments, ``coerce`` and ``empty_value``, as for
  601. :class:`TypedChoiceField`.
  602. ``NullBooleanField``
  603. --------------------
  604. .. class:: NullBooleanField(**kwargs)
  605. * Default widget: :class:`NullBooleanSelect`
  606. * Empty value: ``None``
  607. * Normalizes to: A Python ``True``, ``False`` or ``None`` value.
  608. * Validates nothing (i.e., it never raises a ``ValidationError``).
  609. ``RegexField``
  610. --------------
  611. .. class:: RegexField(**kwargs)
  612. * Default widget: :class:`TextInput`
  613. * Empty value: ``''`` (an empty string)
  614. * Normalizes to: A Unicode object.
  615. * Validates that the given value matches against a certain regular
  616. expression.
  617. * Error message keys: ``required``, ``invalid``
  618. Takes one required argument:
  619. .. attribute:: regex
  620. A regular expression specified either as a string or a compiled regular
  621. expression object.
  622. Also takes ``max_length``, ``min_length``, and ``strip``, which work just
  623. as they do for :class:`CharField`.
  624. .. attribute:: strip
  625. Defaults to ``False``. If enabled, stripping will be applied before the
  626. regex validation.
  627. ``SlugField``
  628. -------------
  629. .. class:: SlugField(**kwargs)
  630. * Default widget: :class:`TextInput`
  631. * Empty value: ``''`` (an empty string)
  632. * Normalizes to: A Unicode object.
  633. * Validates that the given value contains only letters, numbers,
  634. underscores, and hyphens.
  635. * Error messages: ``required``, ``invalid``
  636. This field is intended for use in representing a model
  637. :class:`~django.db.models.SlugField` in forms.
  638. Takes an optional parameter:
  639. .. attribute:: allow_unicode
  640. A boolean instructing the field to accept Unicode letters in addition
  641. to ASCII letters. Defaults to ``False``.
  642. ``TimeField``
  643. -------------
  644. .. class:: TimeField(**kwargs)
  645. * Default widget: :class:`TextInput`
  646. * Empty value: ``None``
  647. * Normalizes to: A Python ``datetime.time`` object.
  648. * Validates that the given value is either a ``datetime.time`` or string
  649. formatted in a particular time format.
  650. * Error message keys: ``required``, ``invalid``
  651. Takes one optional argument:
  652. .. attribute:: input_formats
  653. A list of formats used to attempt to convert a string to a valid
  654. ``datetime.time`` object.
  655. If no ``input_formats`` argument is provided, the default input formats are::
  656. '%H:%M:%S', # '14:30:59'
  657. '%H:%M', # '14:30'
  658. ``URLField``
  659. ------------
  660. .. class:: URLField(**kwargs)
  661. * Default widget: :class:`URLInput`
  662. * Empty value: ``''`` (an empty string)
  663. * Normalizes to: A Unicode object.
  664. * Validates that the given value is a valid URL.
  665. * Error message keys: ``required``, ``invalid``
  666. Takes the following optional arguments:
  667. .. attribute:: max_length
  668. .. attribute:: min_length
  669. These are the same as ``CharField.max_length`` and ``CharField.min_length``.
  670. ``UUIDField``
  671. -------------
  672. .. class:: UUIDField(**kwargs)
  673. * Default widget: :class:`TextInput`
  674. * Empty value: ``''`` (an empty string)
  675. * Normalizes to: A :class:`~python:uuid.UUID` object.
  676. * Error message keys: ``required``, ``invalid``
  677. This field will accept any string format accepted as the ``hex`` argument
  678. to the :class:`~python:uuid.UUID` constructor.
  679. Slightly complex built-in ``Field`` classes
  680. ===========================================
  681. ``ComboField``
  682. --------------
  683. .. class:: ComboField(**kwargs)
  684. * Default widget: :class:`TextInput`
  685. * Empty value: ``''`` (an empty string)
  686. * Normalizes to: A Unicode object.
  687. * Validates the given value against each of the fields specified
  688. as an argument to the ``ComboField``.
  689. * Error message keys: ``required``, ``invalid``
  690. Takes one extra required argument:
  691. .. attribute:: fields
  692. The list of fields that should be used to validate the field's value (in
  693. the order in which they are provided).
  694. >>> from django.forms import ComboField
  695. >>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
  696. >>> f.clean('test@example.com')
  697. 'test@example.com'
  698. >>> f.clean('longemailaddress@example.com')
  699. Traceback (most recent call last):
  700. ...
  701. ValidationError: ['Ensure this value has at most 20 characters (it has 28).']
  702. ``MultiValueField``
  703. -------------------
  704. .. class:: MultiValueField(fields=(), **kwargs)
  705. * Default widget: :class:`TextInput`
  706. * Empty value: ``''`` (an empty string)
  707. * Normalizes to: the type returned by the ``compress`` method of the subclass.
  708. * Validates the given value against each of the fields specified
  709. as an argument to the ``MultiValueField``.
  710. * Error message keys: ``required``, ``invalid``, ``incomplete``
  711. Aggregates the logic of multiple fields that together produce a single
  712. value.
  713. This field is abstract and must be subclassed. In contrast with the
  714. single-value fields, subclasses of :class:`MultiValueField` must not
  715. implement :meth:`~django.forms.Field.clean` but instead - implement
  716. :meth:`~MultiValueField.compress`.
  717. Takes one extra required argument:
  718. .. attribute:: fields
  719. A tuple of fields whose values are cleaned and subsequently combined
  720. into a single value. Each value of the field is cleaned by the
  721. corresponding field in ``fields`` -- the first value is cleaned by the
  722. first field, the second value is cleaned by the second field, etc.
  723. Once all fields are cleaned, the list of clean values is combined into
  724. a single value by :meth:`~MultiValueField.compress`.
  725. Also takes one extra optional argument:
  726. .. attribute:: require_all_fields
  727. Defaults to ``True``, in which case a ``required`` validation error
  728. will be raised if no value is supplied for any field.
  729. When set to ``False``, the :attr:`Field.required` attribute can be set
  730. to ``False`` for individual fields to make them optional. If no value
  731. is supplied for a required field, an ``incomplete`` validation error
  732. will be raised.
  733. A default ``incomplete`` error message can be defined on the
  734. :class:`MultiValueField` subclass, or different messages can be defined
  735. on each individual field. For example::
  736. from django.core.validators import RegexValidator
  737. class PhoneField(MultiValueField):
  738. def __init__(self, *args, **kwargs):
  739. # Define one message for all fields.
  740. error_messages = {
  741. 'incomplete': 'Enter a country calling code and a phone number.',
  742. }
  743. # Or define a different message for each field.
  744. fields = (
  745. CharField(
  746. error_messages={'incomplete': 'Enter a country calling code.'},
  747. validators=[
  748. RegexValidator(r'^[0-9]+$', 'Enter a valid country calling code.'),
  749. ],
  750. ),
  751. CharField(
  752. error_messages={'incomplete': 'Enter a phone number.'},
  753. validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid phone number.')],
  754. ),
  755. CharField(
  756. validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid extension.')],
  757. required=False,
  758. ),
  759. )
  760. super().__init__(
  761. error_messages=error_messages, fields=fields,
  762. require_all_fields=False, *args, **kwargs
  763. )
  764. .. attribute:: MultiValueField.widget
  765. Must be a subclass of :class:`django.forms.MultiWidget`.
  766. Default value is :class:`~django.forms.TextInput`, which
  767. probably is not very useful in this case.
  768. .. method:: compress(data_list)
  769. Takes a list of valid values and returns a "compressed" version of
  770. those values -- in a single value. For example,
  771. :class:`SplitDateTimeField` is a subclass which combines a time field
  772. and a date field into a ``datetime`` object.
  773. This method must be implemented in the subclasses.
  774. ``SplitDateTimeField``
  775. ----------------------
  776. .. class:: SplitDateTimeField(**kwargs)
  777. * Default widget: :class:`SplitDateTimeWidget`
  778. * Empty value: ``None``
  779. * Normalizes to: A Python ``datetime.datetime`` object.
  780. * Validates that the given value is a ``datetime.datetime`` or string
  781. formatted in a particular datetime format.
  782. * Error message keys: ``required``, ``invalid``, ``invalid_date``,
  783. ``invalid_time``
  784. Takes two optional arguments:
  785. .. attribute:: input_date_formats
  786. A list of formats used to attempt to convert a string to a valid
  787. ``datetime.date`` object.
  788. If no ``input_date_formats`` argument is provided, the default input formats
  789. for :class:`DateField` are used.
  790. .. attribute:: input_time_formats
  791. A list of formats used to attempt to convert a string to a valid
  792. ``datetime.time`` object.
  793. If no ``input_time_formats`` argument is provided, the default input formats
  794. for :class:`TimeField` are used.
  795. Fields which handle relationships
  796. =================================
  797. Two fields are available for representing relationships between
  798. models: :class:`ModelChoiceField` and
  799. :class:`ModelMultipleChoiceField`. Both of these fields require a
  800. single ``queryset`` parameter that is used to create the choices for
  801. the field. Upon form validation, these fields will place either one
  802. model object (in the case of ``ModelChoiceField``) or multiple model
  803. objects (in the case of ``ModelMultipleChoiceField``) into the
  804. ``cleaned_data`` dictionary of the form.
  805. For more complex uses, you can specify ``queryset=None`` when declaring the
  806. form field and then populate the ``queryset`` in the form's ``__init__()``
  807. method::
  808. class FooMultipleChoiceForm(forms.Form):
  809. foo_select = forms.ModelMultipleChoiceField(queryset=None)
  810. def __init__(self, *args, **kwargs):
  811. super().__init__(*args, **kwargs)
  812. self.fields['foo_select'].queryset = ...
  813. ``ModelChoiceField``
  814. --------------------
  815. .. class:: ModelChoiceField(**kwargs)
  816. * Default widget: :class:`Select`
  817. * Empty value: ``None``
  818. * Normalizes to: A model instance.
  819. * Validates that the given id exists in the queryset.
  820. * Error message keys: ``required``, ``invalid_choice``
  821. Allows the selection of a single model object, suitable for representing a
  822. foreign key. Note that the default widget for ``ModelChoiceField`` becomes
  823. impractical when the number of entries increases. You should avoid using it
  824. for more than 100 items.
  825. A single argument is required:
  826. .. attribute:: queryset
  827. A ``QuerySet`` of model objects from which the choices for the
  828. field will be derived, and which will be used to validate the
  829. user's selection.
  830. ``ModelChoiceField`` also takes two optional arguments:
  831. .. attribute:: empty_label
  832. By default the ``<select>`` widget used by ``ModelChoiceField`` will have an
  833. empty choice at the top of the list. You can change the text of this
  834. label (which is ``"---------"`` by default) with the ``empty_label``
  835. attribute, or you can disable the empty label entirely by setting
  836. ``empty_label`` to ``None``::
  837. # A custom empty label
  838. field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)")
  839. # No empty label
  840. field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
  841. Note that if a ``ModelChoiceField`` is required and has a default
  842. initial value, no empty choice is created (regardless of the value
  843. of ``empty_label``).
  844. .. attribute:: to_field_name
  845. This optional argument is used to specify the field to use as the value
  846. of the choices in the field's widget. Be sure it's a unique field for
  847. the model, otherwise the selected value could match more than one
  848. object. By default it is set to ``None``, in which case the primary key
  849. of each object will be used. For example::
  850. # No custom to_field_name
  851. field1 = forms.ModelChoiceField(queryset=...)
  852. would yield:
  853. .. code-block:: html
  854. <select id="id_field1" name="field1">
  855. <option value="obj1.pk">Object1</option>
  856. <option value="obj2.pk">Object2</option>
  857. ...
  858. </select>
  859. and::
  860. # to_field_name provided
  861. field2 = forms.ModelChoiceField(queryset=..., to_field_name="name")
  862. would yield:
  863. .. code-block:: html
  864. <select id="id_field2" name="field2">
  865. <option value="obj1.name">Object1</option>
  866. <option value="obj2.name">Object2</option>
  867. ...
  868. </select>
  869. The ``__str__()`` method of the model will be called to generate string
  870. representations of the objects for use in the field's choices. To provide
  871. customized representations, subclass ``ModelChoiceField`` and override
  872. ``label_from_instance``. This method will receive a model object and should
  873. return a string suitable for representing it. For example::
  874. from django.forms import ModelChoiceField
  875. class MyModelChoiceField(ModelChoiceField):
  876. def label_from_instance(self, obj):
  877. return "My Object #%i" % obj.id
  878. ``ModelMultipleChoiceField``
  879. ----------------------------
  880. .. class:: ModelMultipleChoiceField(**kwargs)
  881. * Default widget: :class:`SelectMultiple`
  882. * Empty value: An empty ``QuerySet`` (self.queryset.none())
  883. * Normalizes to: A ``QuerySet`` of model instances.
  884. * Validates that every id in the given list of values exists in the
  885. queryset.
  886. * Error message keys: ``required``, ``list``, ``invalid_choice``,
  887. ``invalid_pk_value``
  888. The ``invalid_choice`` message may contain ``%(value)s`` and the
  889. ``invalid_pk_value`` message may contain ``%(pk)s``, which will be
  890. substituted by the appropriate values.
  891. Allows the selection of one or more model objects, suitable for
  892. representing a many-to-many relation. As with :class:`ModelChoiceField`,
  893. you can use ``label_from_instance`` to customize the object
  894. representations.
  895. A single argument is required:
  896. .. attribute:: queryset
  897. Same as :class:`ModelChoiceField.queryset`.
  898. Takes one optional argument:
  899. .. attribute:: to_field_name
  900. Same as :class:`ModelChoiceField.to_field_name`.
  901. Creating custom fields
  902. ======================
  903. If the built-in ``Field`` classes don't meet your needs, you can easily create
  904. custom ``Field`` classes. To do this, just create a subclass of
  905. ``django.forms.Field``. Its only requirements are that it implement a
  906. ``clean()`` method and that its ``__init__()`` method accept the core arguments
  907. mentioned above (``required``, ``label``, ``initial``, ``widget``,
  908. ``help_text``).
  909. You can also customize how a field will be accessed by overriding
  910. :meth:`~django.forms.Field.get_bound_field()`.