fields.txt 43 KB

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