fields.txt 37 KB

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