fields.txt 36 KB

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