fields.txt 37 KB

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