fields.txt 35 KB

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