fields.txt 35 KB

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