fields.txt 43 KB

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