fields.txt 33 KB

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