fields.txt 37 KB

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