fields.txt 45 KB

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