fields.txt 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  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. Optional. Either ``True`` or ``False``. Default is ``True``. Specifies
  430. whether files in the specified location should be included. Either this or
  431. :attr:`allow_folders` must be ``True``.
  432. .. attribute:: allow_folders
  433. Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
  434. whether folders in the specified location should be included. Either this or
  435. :attr:`allow_files` must be ``True``.
  436. ``FloatField``
  437. ~~~~~~~~~~~~~~
  438. .. class:: FloatField(**kwargs)
  439. * Default widget: :class:`NumberInput` when :attr:`Field.localize` is
  440. ``False``, else :class:`TextInput`.
  441. * Empty value: ``None``
  442. * Normalizes to: A Python float.
  443. * Validates that the given value is an float. Leading and trailing
  444. whitespace is allowed, as in Python's ``float()`` function.
  445. * Error message keys: ``required``, ``invalid``, ``max_value``,
  446. ``min_value``
  447. Takes two optional arguments for validation, ``max_value`` and ``min_value``.
  448. These control the range of values permitted in the field.
  449. ``ImageField``
  450. ~~~~~~~~~~~~~~
  451. .. class:: ImageField(**kwargs)
  452. * Default widget: :class:`ClearableFileInput`
  453. * Empty value: ``None``
  454. * Normalizes to: An ``UploadedFile`` object that wraps the file content
  455. and file name into a single object.
  456. * Validates that file data has been bound to the form, and that the
  457. file is of an image format understood by Pillow/PIL.
  458. * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,
  459. ``invalid_image``
  460. Using an ``ImageField`` requires that either `Pillow`_ (recommended) or the
  461. `Python Imaging Library`_ (PIL) are installed and supports the image
  462. formats you use. If you encounter a ``corrupt image`` error when you
  463. upload an image, it usually means either Pillow or PIL
  464. doesn't understand its format. To fix this, install the appropriate
  465. library and reinstall Pillow or PIL.
  466. When you use an ``ImageField`` on a form, you must also remember to
  467. :ref:`bind the file data to the form <binding-uploaded-files>`.
  468. .. _Pillow: http://python-imaging.github.io/Pillow/
  469. .. _Python Imaging Library: http://www.pythonware.com/products/pil/
  470. ``IntegerField``
  471. ~~~~~~~~~~~~~~~~
  472. .. class:: IntegerField(**kwargs)
  473. * Default widget: :class:`NumberInput` when :attr:`Field.localize` is
  474. ``False``, else :class:`TextInput`.
  475. * Empty value: ``None``
  476. * Normalizes to: A Python integer or long integer.
  477. * Validates that the given value is an integer. Leading and trailing
  478. whitespace is allowed, as in Python's ``int()`` function.
  479. * Error message keys: ``required``, ``invalid``, ``max_value``,
  480. ``min_value``
  481. The ``max_value`` and ``min_value`` error messages may contain
  482. ``%(limit_value)s``, which will be substituted by the appropriate limit.
  483. Takes two optional arguments for validation:
  484. .. attribute:: max_value
  485. .. attribute:: min_value
  486. These control the range of values permitted in the field.
  487. ``IPAddressField``
  488. ~~~~~~~~~~~~~~~~~~
  489. .. class:: IPAddressField(**kwargs)
  490. * Default widget: :class:`TextInput`
  491. * Empty value: ``''`` (an empty string)
  492. * Normalizes to: A Unicode object.
  493. * Validates that the given value is a valid IPv4 address, using a regular
  494. expression.
  495. * Error message keys: ``required``, ``invalid``
  496. ``GenericIPAddressField``
  497. ~~~~~~~~~~~~~~~~~~~~~~~~~
  498. .. class:: GenericIPAddressField(**kwargs)
  499. A field containing either an IPv4 or an IPv6 address.
  500. * Default widget: :class:`TextInput`
  501. * Empty value: ``''`` (an empty string)
  502. * Normalizes to: A Unicode object. IPv6 addresses are
  503. normalized as described below.
  504. * Validates that the given value is a valid IP address.
  505. * Error message keys: ``required``, ``invalid``
  506. The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2,
  507. including using the IPv4 format suggested in paragraph 3 of that section, like
  508. ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to
  509. ``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters
  510. are converted to lowercase.
  511. Takes two optional arguments:
  512. .. attribute:: protocol
  513. Limits valid inputs to the specified protocol.
  514. Accepted values are ``both`` (default), ``IPv4``
  515. or ``IPv6``. Matching is case insensitive.
  516. .. attribute:: unpack_ipv4
  517. Unpacks IPv4 mapped addresses like ``::ffff:192.0.2.1``.
  518. If this option is enabled that address would be unpacked to
  519. ``192.0.2.1``. Default is disabled. Can only be used
  520. when ``protocol`` is set to ``'both'``.
  521. ``MultipleChoiceField``
  522. ~~~~~~~~~~~~~~~~~~~~~~~
  523. .. class:: MultipleChoiceField(**kwargs)
  524. * Default widget: :class:`SelectMultiple`
  525. * Empty value: ``[]`` (an empty list)
  526. * Normalizes to: A list of Unicode objects.
  527. * Validates that every value in the given list of values exists in the list
  528. of choices.
  529. * Error message keys: ``required``, ``invalid_choice``, ``invalid_list``
  530. The ``invalid_choice`` error message may contain ``%(value)s``, which will be
  531. replaced with the selected choice.
  532. Takes one extra required argument, ``choices``, as for ``ChoiceField``.
  533. ``TypedMultipleChoiceField``
  534. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  535. .. class:: TypedMultipleChoiceField(**kwargs)
  536. Just like a :class:`MultipleChoiceField`, except :class:`TypedMultipleChoiceField`
  537. takes two extra arguments, ``coerce`` and ``empty_value``.
  538. * Default widget: :class:`SelectMultiple`
  539. * Empty value: Whatever you've given as ``empty_value``
  540. * Normalizes to: A list of values of the type provided by the ``coerce``
  541. argument.
  542. * Validates that the given values exists in the list of choices and can be
  543. coerced.
  544. * Error message keys: ``required``, ``invalid_choice``
  545. The ``invalid_choice`` error message may contain ``%(value)s``, which will be
  546. replaced with the selected choice.
  547. Takes two extra arguments, ``coerce`` and ``empty_value``, as for ``TypedChoiceField``.
  548. ``NullBooleanField``
  549. ~~~~~~~~~~~~~~~~~~~~
  550. .. class:: NullBooleanField(**kwargs)
  551. * Default widget: :class:`NullBooleanSelect`
  552. * Empty value: ``None``
  553. * Normalizes to: A Python ``True``, ``False`` or ``None`` value.
  554. * Validates nothing (i.e., it never raises a ``ValidationError``).
  555. ``RegexField``
  556. ~~~~~~~~~~~~~~
  557. .. class:: RegexField(**kwargs)
  558. * Default widget: :class:`TextInput`
  559. * Empty value: ``''`` (an empty string)
  560. * Normalizes to: A Unicode object.
  561. * Validates that the given value matches against a certain regular
  562. expression.
  563. * Error message keys: ``required``, ``invalid``
  564. Takes one required argument:
  565. .. attribute:: regex
  566. A regular expression specified either as a string or a compiled regular
  567. expression object.
  568. Also takes ``max_length`` and ``min_length``, which work just as they do for
  569. ``CharField``.
  570. The optional argument ``error_message`` is also accepted for backwards
  571. compatibility. The preferred way to provide an error message is to use the
  572. ``error_messages`` argument, passing a dictionary with ``'invalid'`` as a key
  573. and the error message as the value.
  574. ``SlugField``
  575. ~~~~~~~~~~~~~
  576. .. class:: SlugField(**kwargs)
  577. * Default widget: :class:`TextInput`
  578. * Empty value: ``''`` (an empty string)
  579. * Normalizes to: A Unicode object.
  580. * Validates that the given value contains only letters, numbers,
  581. underscores, and hyphens.
  582. * Error messages: ``required``, ``invalid``
  583. This field is intended for use in representing a model
  584. :class:`~django.db.models.SlugField` in forms.
  585. ``TimeField``
  586. ~~~~~~~~~~~~~
  587. .. class:: TimeField(**kwargs)
  588. * Default widget: :class:`TextInput`
  589. * Empty value: ``None``
  590. * Normalizes to: A Python ``datetime.time`` object.
  591. * Validates that the given value is either a ``datetime.time`` or string
  592. formatted in a particular time format.
  593. * Error message keys: ``required``, ``invalid``
  594. Takes one optional argument:
  595. .. attribute:: input_formats
  596. A list of formats used to attempt to convert a string to a valid
  597. ``datetime.time`` object.
  598. If no ``input_formats`` argument is provided, the default input formats are::
  599. '%H:%M:%S', # '14:30:59'
  600. '%H:%M', # '14:30'
  601. ``URLField``
  602. ~~~~~~~~~~~~
  603. .. class:: URLField(**kwargs)
  604. * Default widget: :class:`URLInput`
  605. * Empty value: ``''`` (an empty string)
  606. * Normalizes to: A Unicode object.
  607. * Validates that the given value is a valid URL.
  608. * Error message keys: ``required``, ``invalid``
  609. Takes the following optional arguments:
  610. .. attribute:: max_length
  611. .. attribute:: min_length
  612. These are the same as ``CharField.max_length`` and ``CharField.min_length``.
  613. Slightly complex built-in ``Field`` classes
  614. -------------------------------------------
  615. ``ComboField``
  616. ~~~~~~~~~~~~~~
  617. .. class:: ComboField(**kwargs)
  618. * Default widget: :class:`TextInput`
  619. * Empty value: ``''`` (an empty string)
  620. * Normalizes to: A Unicode object.
  621. * Validates that the given value against each of the fields specified
  622. as an argument to the ``ComboField``.
  623. * Error message keys: ``required``, ``invalid``
  624. Takes one extra required argument:
  625. .. attribute:: fields
  626. The list of fields that should be used to validate the field's value (in
  627. the order in which they are provided).
  628. >>> from django.forms import ComboField
  629. >>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
  630. >>> f.clean('test@example.com')
  631. u'test@example.com'
  632. >>> f.clean('longemailaddress@example.com')
  633. Traceback (most recent call last):
  634. ...
  635. ValidationError: [u'Ensure this value has at most 20 characters (it has 28).']
  636. ``MultiValueField``
  637. ~~~~~~~~~~~~~~~~~~~
  638. .. class:: MultiValueField(fields=(), **kwargs)
  639. * Default widget: :class:`TextInput`
  640. * Empty value: ``''`` (an empty string)
  641. * Normalizes to: the type returned by the ``compress`` method of the subclass.
  642. * Validates that the given value against each of the fields specified
  643. as an argument to the ``MultiValueField``.
  644. * Error message keys: ``required``, ``invalid``, ``incomplete``
  645. Aggregates the logic of multiple fields that together produce a single
  646. value.
  647. This field is abstract and must be subclassed. In contrast with the
  648. single-value fields, subclasses of :class:`MultiValueField` must not
  649. implement :meth:`~django.forms.Field.clean` but instead - implement
  650. :meth:`~MultiValueField.compress`.
  651. Takes one extra required argument:
  652. .. attribute:: fields
  653. A tuple of fields whose values are cleaned and subsequently combined
  654. into a single value. Each value of the field is cleaned by the
  655. corresponding field in ``fields`` -- the first value is cleaned by the
  656. first field, the second value is cleaned by the second field, etc.
  657. Once all fields are cleaned, the list of clean values is combined into
  658. a single value by :meth:`~MultiValueField.compress`.
  659. Also takes one extra optional argument:
  660. .. attribute:: require_all_fields
  661. .. versionadded:: 1.7
  662. Defaults to ``True``, in which case a ``required`` validation error
  663. will be raised if no value is supplied for any field.
  664. When set to ``False``, the :attr:`Field.required` attribute can be set
  665. to ``False`` for individual fields to make them optional. If no value
  666. is supplied for a required field, an ``incomplete`` validation error
  667. will be raised.
  668. A default ``incomplete`` error message can be defined on the
  669. :class:`MultiValueField` subclass, or different messages can be defined
  670. on each individual field. For example::
  671. from django.core.validators import RegexValidator
  672. class PhoneField(MultiValueField):
  673. def __init__(self, *args, **kwargs):
  674. # Define one message for all fields.
  675. error_messages = {
  676. 'incomplete': 'Enter a country code and phone number.',
  677. }
  678. # Or define a different message for each field.
  679. fields = (
  680. CharField(error_messages={'incomplete': 'Enter a country code.'},
  681. validators=[RegexValidator(r'^\d+$', 'Enter a valid country code.')]),
  682. CharField(error_messages={'incomplete': 'Enter a phone number.'},
  683. validators=[RegexValidator(r'^\d+$', 'Enter a valid phone number.')]),
  684. CharField(validators=[RegexValidator(r'^\d+$', 'Enter a valid extension.')],
  685. required=False),
  686. )
  687. super(PhoneField, self).__init__(
  688. self, error_messages=error_messages, fields=fields,
  689. require_all_fields=False, *args, **kwargs)
  690. .. attribute:: MultiValueField.widget
  691. Must be a subclass of :class:`django.forms.MultiWidget`.
  692. Default value is :class:`~django.forms.TextInput`, which
  693. probably is not very useful in this case.
  694. .. method:: compress(data_list)
  695. Takes a list of valid values and returns a "compressed" version of
  696. those values -- in a single value. For example,
  697. :class:`SplitDateTimeField` is a subclass which combines a time field
  698. and a date field into a ``datetime`` object.
  699. This method must be implemented in the subclasses.
  700. ``SplitDateTimeField``
  701. ~~~~~~~~~~~~~~~~~~~~~~
  702. .. class:: SplitDateTimeField(**kwargs)
  703. * Default widget: :class:`SplitDateTimeWidget`
  704. * Empty value: ``None``
  705. * Normalizes to: A Python ``datetime.datetime`` object.
  706. * Validates that the given value is a ``datetime.datetime`` or string
  707. formatted in a particular datetime format.
  708. * Error message keys: ``required``, ``invalid``, ``invalid_date``,
  709. ``invalid_time``
  710. Takes two optional arguments:
  711. .. attribute:: input_date_formats
  712. A list of formats used to attempt to convert a string to a valid
  713. ``datetime.date`` object.
  714. If no ``input_date_formats`` argument is provided, the default input formats
  715. for ``DateField`` are used.
  716. .. attribute:: input_time_formats
  717. A list of formats used to attempt to convert a string to a valid
  718. ``datetime.time`` object.
  719. If no ``input_time_formats`` argument is provided, the default input formats
  720. for ``TimeField`` are used.
  721. Fields which handle relationships
  722. ---------------------------------
  723. Two fields are available for representing relationships between
  724. models: :class:`ModelChoiceField` and
  725. :class:`ModelMultipleChoiceField`. Both of these fields require a
  726. single ``queryset`` parameter that is used to create the choices for
  727. the field. Upon form validation, these fields will place either one
  728. model object (in the case of ``ModelChoiceField``) or multiple model
  729. objects (in the case of ``ModelMultipleChoiceField``) into the
  730. ``cleaned_data`` dictionary of the form.
  731. ``ModelChoiceField``
  732. ~~~~~~~~~~~~~~~~~~~~
  733. .. class:: ModelChoiceField(**kwargs)
  734. * Default widget: :class:`Select`
  735. * Empty value: ``None``
  736. * Normalizes to: A model instance.
  737. * Validates that the given id exists in the queryset.
  738. * Error message keys: ``required``, ``invalid_choice``
  739. Allows the selection of a single model object, suitable for representing a
  740. foreign key. Note that the default widget for ``ModelChoiceField`` becomes
  741. impractical when the number of entries increases. You should avoid using it
  742. for more than 100 items.
  743. A single argument is required:
  744. .. attribute:: queryset
  745. A ``QuerySet`` of model objects from which the choices for the
  746. field will be derived, and which will be used to validate the
  747. user's selection.
  748. ``ModelChoiceField`` also takes one optional argument:
  749. .. attribute:: empty_label
  750. By default the ``<select>`` widget used by ``ModelChoiceField`` will have an
  751. empty choice at the top of the list. You can change the text of this
  752. label (which is ``"---------"`` by default) with the ``empty_label``
  753. attribute, or you can disable the empty label entirely by setting
  754. ``empty_label`` to ``None``::
  755. # A custom empty label
  756. field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)")
  757. # No empty label
  758. field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
  759. Note that if a ``ModelChoiceField`` is required and has a default
  760. initial value, no empty choice is created (regardless of the value
  761. of ``empty_label``).
  762. The ``__unicode__`` (``__str__`` on Python 3) method of the model will be
  763. called to generate string representations of the objects for use in the
  764. field's choices; to provide customized representations, subclass
  765. ``ModelChoiceField`` and override ``label_from_instance``. This method will
  766. receive a model object, and should return a string suitable for representing
  767. it. For example::
  768. from django.forms import ModelChoiceField
  769. class MyModelChoiceField(ModelChoiceField):
  770. def label_from_instance(self, obj):
  771. return "My Object #%i" % obj.id
  772. ``ModelMultipleChoiceField``
  773. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  774. .. class:: ModelMultipleChoiceField(**kwargs)
  775. * Default widget: :class:`SelectMultiple`
  776. * Empty value: An empty ``QuerySet`` (self.queryset.none())
  777. * Normalizes to: A ``QuerySet`` of model instances.
  778. * Validates that every id in the given list of values exists in the
  779. queryset.
  780. * Error message keys: ``required``, ``list``, ``invalid_choice``,
  781. ``invalid_pk_value``
  782. .. versionchanged:: 1.6
  783. The ``invalid_choice`` message may contain ``%(value)s`` and the
  784. ``invalid_pk_value`` message may contain ``%(pk)s``, which will be
  785. substituted by the appropriate values.
  786. Allows the selection of one or more model objects, suitable for
  787. representing a many-to-many relation. As with :class:`ModelChoiceField`,
  788. you can use ``label_from_instance`` to customize the object
  789. representations, and ``queryset`` is a required parameter:
  790. .. attribute:: queryset
  791. A ``QuerySet`` of model objects from which the choices for the
  792. field will be derived, and which will be used to validate the
  793. user's selection.
  794. Creating custom fields
  795. ----------------------
  796. If the built-in ``Field`` classes don't meet your needs, you can easily create
  797. custom ``Field`` classes. To do this, just create a subclass of
  798. ``django.forms.Field``. Its only requirements are that it implement a
  799. ``clean()`` method and that its ``__init__()`` method accept the core arguments
  800. mentioned above (``required``, ``label``, ``initial``, ``widget``,
  801. ``help_text``).