fields.txt 44 KB

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