fields.txt 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  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:: CharField.max_length
  253. .. attribute:: CharField.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:: ChoiceField.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:: TypedChoiceField.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:: TypedChoiceField.empty_value
  289. The value to use to represent "empty." Defaults to the empty string;
  290. ``None`` is another common choice here.
  291. ``DateField``
  292. ~~~~~~~~~~~~~
  293. .. class:: DateField(**kwargs)
  294. * Default widget: ``DateInput``
  295. * Empty value: ``None``
  296. * Normalizes to: A Python ``datetime.date`` object.
  297. * Validates that the given value is either a ``datetime.date``,
  298. ``datetime.datetime`` or string formatted in a particular date format.
  299. * Error message keys: ``required``, ``invalid``
  300. Takes one optional argument:
  301. .. attribute:: DateField.input_formats
  302. A list of formats used to attempt to convert a string to a valid
  303. ``datetime.date`` object.
  304. If no ``input_formats`` argument is provided, the default input formats are::
  305. '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
  306. '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'
  307. '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'
  308. '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006'
  309. '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'
  310. ``DateTimeField``
  311. ~~~~~~~~~~~~~~~~~
  312. .. class:: DateTimeField(**kwargs)
  313. * Default widget: ``DateTimeInput``
  314. * Empty value: ``None``
  315. * Normalizes to: A Python ``datetime.datetime`` object.
  316. * Validates that the given value is either a ``datetime.datetime``,
  317. ``datetime.date`` or string formatted in a particular datetime format.
  318. * Error message keys: ``required``, ``invalid``
  319. Takes one optional argument:
  320. .. attribute:: DateTimeField.input_formats
  321. A list of formats used to attempt to convert a string to a valid
  322. ``datetime.datetime`` object.
  323. If no ``input_formats`` argument is provided, the default input formats are::
  324. '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
  325. '%Y-%m-%d %H:%M', # '2006-10-25 14:30'
  326. '%Y-%m-%d', # '2006-10-25'
  327. '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
  328. '%m/%d/%Y %H:%M', # '10/25/2006 14:30'
  329. '%m/%d/%Y', # '10/25/2006'
  330. '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
  331. '%m/%d/%y %H:%M', # '10/25/06 14:30'
  332. '%m/%d/%y', # '10/25/06'
  333. ``DecimalField``
  334. ~~~~~~~~~~~~~~~~
  335. .. class:: DecimalField(**kwargs)
  336. * Default widget: ``TextInput``
  337. * Empty value: ``None``
  338. * Normalizes to: A Python ``decimal``.
  339. * Validates that the given value is a decimal. Leading and trailing
  340. whitespace is ignored.
  341. * Error message keys: ``required``, ``invalid``, ``max_value``,
  342. ``min_value``, ``max_digits``, ``max_decimal_places``,
  343. ``max_whole_digits``
  344. The ``max_value`` and ``min_value`` error messages may contain
  345. ``%(limit_value)s``, which will be substituted by the appropriate limit.
  346. Takes four optional arguments:
  347. .. attribute:: DecimalField.max_value
  348. .. attribute:: DecimalField.min_value
  349. These control the range of values permitted in the field, and should be
  350. given as ``decimal.Decimal`` values.
  351. .. attribute:: DecimalField.max_digits
  352. The maximum number of digits (those before the decimal point plus those
  353. after the decimal point, with leading zeros stripped) permitted in the
  354. value.
  355. .. attribute:: DecimalField.decimal_places
  356. The maximum number of decimal places permitted.
  357. ``EmailField``
  358. ~~~~~~~~~~~~~~
  359. .. class:: EmailField(**kwargs)
  360. * Default widget: ``TextInput``
  361. * Empty value: ``''`` (an empty string)
  362. * Normalizes to: A Unicode object.
  363. * Validates that the given value is a valid email address, using a
  364. moderately complex regular expression.
  365. * Error message keys: ``required``, ``invalid``
  366. Has two optional arguments for validation, ``max_length`` and ``min_length``.
  367. If provided, these arguments ensure that the string is at most or at least the
  368. given length.
  369. .. versionchanged:: 1.2
  370. The EmailField previously did not recognize email addresses as valid that
  371. contained an IDN (Internationalized Domain Name; a domain containing
  372. unicode characters) domain part. This has now been corrected.
  373. ``FileField``
  374. ~~~~~~~~~~~~~
  375. .. class:: FileField(**kwargs)
  376. * Default widget: ``ClearableFileInput``
  377. * Empty value: ``None``
  378. * Normalizes to: An ``UploadedFile`` object that wraps the file content
  379. and file name into a single object.
  380. * Can validate that non-empty file data has been bound to the form.
  381. * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,
  382. ``max_length``
  383. Has two optional arguments for validation, ''max_length'' and
  384. ''allow_empty_file''. If provided, these ensure that the file name is at
  385. most the given length, and that validation will succeed even if the file
  386. content is empty.
  387. To learn more about the ``UploadedFile`` object, see the :doc:`file uploads
  388. documentation </topics/http/file-uploads>`.
  389. When you use a ``FileField`` in a form, you must also remember to
  390. :ref:`bind the file data to the form <binding-uploaded-files>`.
  391. The ``max_length`` error refers to the length of the filename. In the error
  392. message for that key, ``%(max)d`` will be replaced with the maximum filename
  393. length and ``%(length)d`` will be replaced with the current filename length.
  394. ``FilePathField``
  395. ~~~~~~~~~~~~~~~~~
  396. .. class:: FilePathField(**kwargs)
  397. * Default widget: ``Select``
  398. * Empty value: ``None``
  399. * Normalizes to: A unicode object
  400. * Validates that the selected choice exists in the list of choices.
  401. * Error message keys: ``required``, ``invalid_choice``
  402. The field allows choosing from files inside a certain directory. It takes three
  403. extra arguments; only ``path`` is required:
  404. .. attribute:: FilePathField.path
  405. The absolute path to the directory whose contents you want listed. This
  406. directory must exist.
  407. .. attribute:: FilePathField.recursive
  408. If ``False`` (the default) only the direct contents of ``path`` will be
  409. offered as choices. If ``True``, the directory will be descended into
  410. recursively and all descendants will be listed as choices.
  411. .. attribute:: FilePathField.match
  412. A regular expression pattern; only files with names matching this expression
  413. will be allowed as choices.
  414. ``FloatField``
  415. ~~~~~~~~~~~~~~
  416. * Default widget: ``TextInput``
  417. * Empty value: ``None``
  418. * Normalizes to: A Python float.
  419. * Validates that the given value is an float. Leading and trailing
  420. whitespace is allowed, as in Python's ``float()`` function.
  421. * Error message keys: ``required``, ``invalid``, ``max_value``,
  422. ``min_value``
  423. Takes two optional arguments for validation, ``max_value`` and ``min_value``.
  424. These control the range of values permitted in the field.
  425. ``ImageField``
  426. ~~~~~~~~~~~~~~
  427. .. class:: ImageField(**kwargs)
  428. * Default widget: ``ClearableFileInput``
  429. * Empty value: ``None``
  430. * Normalizes to: An ``UploadedFile`` object that wraps the file content
  431. and file name into a single object.
  432. * Validates that file data has been bound to the form, and that the
  433. file is of an image format understood by PIL.
  434. * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,
  435. ``invalid_image``
  436. Using an ImageField requires that the `Python Imaging Library`_ is installed.
  437. When you use an ``ImageField`` on a form, you must also remember to
  438. :ref:`bind the file data to the form <binding-uploaded-files>`.
  439. .. _Python Imaging Library: http://www.pythonware.com/products/pil/
  440. ``IntegerField``
  441. ~~~~~~~~~~~~~~~~
  442. .. class:: IntegerField(**kwargs)
  443. * Default widget: ``TextInput``
  444. * Empty value: ``None``
  445. * Normalizes to: A Python integer or long integer.
  446. * Validates that the given value is an integer. Leading and trailing
  447. whitespace is allowed, as in Python's ``int()`` function.
  448. * Error message keys: ``required``, ``invalid``, ``max_value``,
  449. ``min_value``
  450. The ``max_value`` and ``min_value`` error messages may contain
  451. ``%(limit_value)s``, which will be substituted by the appropriate limit.
  452. Takes two optional arguments for validation:
  453. .. attribute:: IntegerField.max_value
  454. .. attribute:: IntegerField.min_value
  455. These control the range of values permitted in the field.
  456. ``IPAddressField``
  457. ~~~~~~~~~~~~~~~~~~
  458. .. class:: IPAddressField(**kwargs)
  459. * Default widget: ``TextInput``
  460. * Empty value: ``''`` (an empty string)
  461. * Normalizes to: A Unicode object.
  462. * Validates that the given value is a valid IPv4 address, using a regular
  463. expression.
  464. * Error message keys: ``required``, ``invalid``
  465. ``GenericIPAddressField``
  466. ~~~~~~~~~~~~~~~~~~~~~~~~~
  467. .. class:: GenericIPAddressField(**kwargs)
  468. .. versionadded:: 1.4
  469. A field containing either an IPv4 or an IPv6 address.
  470. * Default widget: ``TextInput``
  471. * Empty value: ``''`` (an empty string)
  472. * Normalizes to: A Unicode object. IPv6 addresses are
  473. normalized as described below.
  474. * Validates that the given value is a valid IP address.
  475. * Error message keys: ``required``, ``invalid``
  476. The IPv6 address normalization follows `RFC4291 section 2.2`_, including using
  477. the IPv4 format suggested in paragraph 3 of that section, like
  478. ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to
  479. ``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All
  480. characters are converted to lowercase.
  481. .. _RFC4291 section 2.2: http://tools.ietf.org/html/rfc4291#section-2.2
  482. Takes two optional arguments:
  483. .. attribute:: GenericIPAddressField.protocol
  484. Limits valid inputs to the specified protocol.
  485. Accepted values are ``both`` (default), ``IPv4``
  486. or ``IPv6``. Matching is case insensitive.
  487. .. attribute:: GenericIPAddressField.unpack_ipv4
  488. Unpacks IPv4 mapped addresses like ``::ffff::192.0.2.1``.
  489. If this option is enabled that address would be unpacked to
  490. ``192.0.2.1``. Default is disabled. Can only be used
  491. when ``protocol`` is set to ``'both'``.
  492. ``MultipleChoiceField``
  493. ~~~~~~~~~~~~~~~~~~~~~~~
  494. .. class:: MultipleChoiceField(**kwargs)
  495. * Default widget: ``SelectMultiple``
  496. * Empty value: ``[]`` (an empty list)
  497. * Normalizes to: A list of Unicode objects.
  498. * Validates that every value in the given list of values exists in the list
  499. of choices.
  500. * Error message keys: ``required``, ``invalid_choice``, ``invalid_list``
  501. The ``invalid_choice`` error message may contain ``%(value)s``, which will be
  502. replaced with the selected choice.
  503. Takes one extra required argument, ``choices``, as for ``ChoiceField``.
  504. ``TypedMultipleChoiceField``
  505. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  506. .. class:: TypedMultipleChoiceField(**kwargs)
  507. .. versionadded:: 1.3
  508. Just like a :class:`MultipleChoiceField`, except :class:`TypedMultipleChoiceField`
  509. takes two extra arguments, ``coerce`` and ``empty_value``.
  510. * Default widget: ``SelectMultiple``
  511. * Empty value: Whatever you've given as ``empty_value``
  512. * Normalizes to: A list of values of the type provided by the ``coerce``
  513. argument.
  514. * Validates that the given values exists in the list of choices and can be
  515. coerced.
  516. * Error message keys: ``required``, ``invalid_choice``
  517. The ``invalid_choice`` error message may contain ``%(value)s``, which will be
  518. replaced with the selected choice.
  519. Takes two extra arguments, ``coerce`` and ``empty_value``, as for ``TypedChoiceField``.
  520. ``NullBooleanField``
  521. ~~~~~~~~~~~~~~~~~~~~
  522. .. class:: NullBooleanField(**kwargs)
  523. * Default widget: ``NullBooleanSelect``
  524. * Empty value: ``None``
  525. * Normalizes to: A Python ``True``, ``False`` or ``None`` value.
  526. * Validates nothing (i.e., it never raises a ``ValidationError``).
  527. ``RegexField``
  528. ~~~~~~~~~~~~~~
  529. .. class:: RegexField(**kwargs)
  530. * Default widget: ``TextInput``
  531. * Empty value: ``''`` (an empty string)
  532. * Normalizes to: A Unicode object.
  533. * Validates that the given value matches against a certain regular
  534. expression.
  535. * Error message keys: ``required``, ``invalid``
  536. Takes one required argument:
  537. .. attribute:: RegexField.regex
  538. A regular expression specified either as a string or a compiled regular
  539. expression object.
  540. Also takes ``max_length`` and ``min_length``, which work just as they do for
  541. ``CharField``.
  542. The optional argument ``error_message`` is also accepted for backwards
  543. compatibility. The preferred way to provide an error message is to use the
  544. ``error_messages`` argument, passing a dictionary with ``'invalid'`` as a key
  545. and the error message as the value.
  546. ``SlugField``
  547. ~~~~~~~~~~~~~
  548. .. class:: SlugField(**kwargs)
  549. * Default widget: ``TextInput``
  550. * Empty value: ``''`` (an empty string)
  551. * Normalizes to: A Unicode object.
  552. * Validates that the given value contains only letters, numbers,
  553. underscores, and hyphens.
  554. * Error messages: ``required``, ``invalid``
  555. This field is intended for use in representing a model
  556. :class:`~django.db.models.SlugField` in forms.
  557. ``TimeField``
  558. ~~~~~~~~~~~~~
  559. .. class:: TimeField(**kwargs)
  560. * Default widget: ``TextInput``
  561. * Empty value: ``None``
  562. * Normalizes to: A Python ``datetime.time`` object.
  563. * Validates that the given value is either a ``datetime.time`` or string
  564. formatted in a particular time format.
  565. * Error message keys: ``required``, ``invalid``
  566. Takes one optional argument:
  567. .. attribute:: TimeField.input_formats
  568. A list of formats used to attempt to convert a string to a valid
  569. ``datetime.time`` object.
  570. If no ``input_formats`` argument is provided, the default input formats are::
  571. '%H:%M:%S', # '14:30:59'
  572. '%H:%M', # '14:30'
  573. ``URLField``
  574. ~~~~~~~~~~~~
  575. .. class:: URLField(**kwargs)
  576. * Default widget: ``TextInput``
  577. * Empty value: ``''`` (an empty string)
  578. * Normalizes to: A Unicode object.
  579. * Validates that the given value is a valid URL.
  580. * Error message keys: ``required``, ``invalid``, ``invalid_link``
  581. Takes the following optional arguments:
  582. .. attribute:: URLField.max_length
  583. .. attribute:: URLField.min_length
  584. Same as ``CharField.max_length`` and ``CharField.min_length``.
  585. .. attribute:: URLField.verify_exists
  586. If ``True``, the validator will attempt to load the given URL, raising
  587. ``ValidationError`` if the page gives a 404. Defaults to ``False``.
  588. .. attribute:: URLField.validator_user_agent
  589. String used as the user-agent used when checking for a URL's existence.
  590. Defaults to the value of the :setting:`URL_VALIDATOR_USER_AGENT` setting.
  591. .. versionchanged:: 1.2
  592. The URLField previously did not recognize URLs as valid that contained an IDN
  593. (Internationalized Domain Name; a domain name containing unicode characters)
  594. domain name. This has now been corrected.
  595. Slightly complex built-in ``Field`` classes
  596. -------------------------------------------
  597. ``ComboField``
  598. ~~~~~~~~~~~~~~
  599. .. class:: ComboField(**kwargs)
  600. * Default widget: ``TextInput``
  601. * Empty value: ``''`` (an empty string)
  602. * Normalizes to: A Unicode object.
  603. * Validates that the given value against each of the fields specified
  604. as an argument to the ``ComboField``.
  605. * Error message keys: ``required``, ``invalid``
  606. Takes one extra required argument:
  607. .. attribute:: ComboField.fields
  608. The list of fields that should be used to validate the field's value (in
  609. the order in which they are provided).
  610. >>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
  611. >>> f.clean('test@example.com')
  612. u'test@example.com'
  613. >>> f.clean('longemailaddress@example.com')
  614. Traceback (most recent call last):
  615. ...
  616. ValidationError: [u'Ensure this value has at most 20 characters (it has 28).']
  617. ``MultiValueField``
  618. ~~~~~~~~~~~~~~~~~~~
  619. .. class:: MultiValueField(**kwargs)
  620. * Default widget: ``TextInput``
  621. * Empty value: ``''`` (an empty string)
  622. * Normalizes to: the type returned by the ``compress`` method of the subclass.
  623. * Validates that the given value against each of the fields specified
  624. as an argument to the ``MultiValueField``.
  625. * Error message keys: ``required``, ``invalid``
  626. This abstract field (must be subclassed) aggregates the logic of multiple
  627. fields. Subclasses should not have to implement clean(). Instead, they must
  628. implement compress(), which takes a list of valid values and returns a
  629. "compressed" version of those values -- a single value. For example,
  630. :class:`SplitDateTimeField` is a subclass which combines a time field and
  631. a date field into a datetime object.
  632. Takes one extra required argument:
  633. .. attribute:: MultiValueField.fields
  634. A list of fields which are cleaned into a single field. Each value in
  635. ``clean`` is cleaned by the corresponding field in ``fields`` -- the first
  636. value is cleaned by the first field, the second value is cleaned by
  637. the second field, etc. Once all fields are cleaned, the list of clean
  638. values is "compressed" into a single value.
  639. ``SplitDateTimeField``
  640. ~~~~~~~~~~~~~~~~~~~~~~
  641. .. class:: SplitDateTimeField(**kwargs)
  642. * Default widget: ``SplitDateTimeWidget``
  643. * Empty value: ``None``
  644. * Normalizes to: A Python ``datetime.datetime`` object.
  645. * Validates that the given value is a ``datetime.datetime`` or string
  646. formatted in a particular datetime format.
  647. * Error message keys: ``required``, ``invalid``, ``invalid_date``,
  648. ``invalid_time``
  649. Takes two optional arguments:
  650. .. attribute:: SplitDateTimeField.input_date_formats
  651. A list of formats used to attempt to convert a string to a valid
  652. ``datetime.date`` object.
  653. If no ``input_date_formats`` argument is provided, the default input formats
  654. for ``DateField`` are used.
  655. .. attribute:: SplitDateTimeField.input_time_formats
  656. A list of formats used to attempt to convert a string to a valid
  657. ``datetime.time`` object.
  658. If no ``input_time_formats`` argument is provided, the default input formats
  659. for ``TimeField`` are used.
  660. Fields which handle relationships
  661. ---------------------------------
  662. Two fields are available for representing relationships between
  663. models: :class:`ModelChoiceField` and
  664. :class:`ModelMultipleChoiceField`. Both of these fields require a
  665. single ``queryset`` parameter that is used to create the choices for
  666. the field. Upon form validation, these fields will place either one
  667. model object (in the case of ``ModelChoiceField``) or multiple model
  668. objects (in the case of ``ModelMultipleChoiceField``) into the
  669. ``cleaned_data`` dictionary of the form.
  670. ``ModelChoiceField``
  671. ~~~~~~~~~~~~~~~~~~~~
  672. .. class:: ModelChoiceField(**kwargs)
  673. * Default widget: ``Select``
  674. * Empty value: ``None``
  675. * Normalizes to: A model instance.
  676. * Validates that the given id exists in the queryset.
  677. * Error message keys: ``required``, ``invalid_choice``
  678. Allows the selection of a single model object, suitable for
  679. representing a foreign key. A single argument is required:
  680. .. attribute:: ModelChoiceField.queryset
  681. A ``QuerySet`` of model objects from which the choices for the
  682. field will be derived, and which will be used to validate the
  683. user's selection.
  684. ``ModelChoiceField`` also takes one optional argument:
  685. .. attribute:: ModelChoiceField.empty_label
  686. By default the ``<select>`` widget used by ``ModelChoiceField`` will have an
  687. empty choice at the top of the list. You can change the text of this
  688. label (which is ``"---------"`` by default) with the ``empty_label``
  689. attribute, or you can disable the empty label entirely by setting
  690. ``empty_label`` to ``None``::
  691. # A custom empty label
  692. field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)")
  693. # No empty label
  694. field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
  695. Note that if a ``ModelChoiceField`` is required and has a default
  696. initial value, no empty choice is created (regardless of the value
  697. of ``empty_label``).
  698. The ``__unicode__`` method of the model will be called to generate
  699. string representations of the objects for use in the field's choices;
  700. to provide customized representations, subclass ``ModelChoiceField``
  701. and override ``label_from_instance``. This method will receive a model
  702. object, and should return a string suitable for representing it. For
  703. example::
  704. class MyModelChoiceField(ModelChoiceField):
  705. def label_from_instance(self, obj):
  706. return "My Object #%i" % obj.id
  707. ``ModelMultipleChoiceField``
  708. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  709. .. class:: ModelMultipleChoiceField(**kwargs)
  710. * Default widget: ``SelectMultiple``
  711. * Empty value: ``[]`` (an empty list)
  712. * Normalizes to: A list of model instances.
  713. * Validates that every id in the given list of values exists in the
  714. queryset.
  715. * Error message keys: ``required``, ``list``, ``invalid_choice``,
  716. ``invalid_pk_value``
  717. Allows the selection of one or more model objects, suitable for
  718. representing a many-to-many relation. As with :class:`ModelChoiceField`,
  719. you can use ``label_from_instance`` to customize the object
  720. representations, and ``queryset`` is a required parameter:
  721. .. attribute:: ModelMultipleChoiceField.queryset
  722. A ``QuerySet`` of model objects from which the choices for the
  723. field will be derived, and which will be used to validate the
  724. user's selection.
  725. Creating custom fields
  726. ----------------------
  727. If the built-in ``Field`` classes don't meet your needs, you can easily create
  728. custom ``Field`` classes. To do this, just create a subclass of
  729. ``django.forms.Field``. Its only requirements are that it implement a
  730. ``clean()`` method and that its ``__init__()`` method accept the core arguments
  731. mentioned above (``required``, ``label``, ``initial``, ``widget``,
  732. ``help_text``).