fields.txt 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628
  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
  16. ``django.core.exceptions.ValidationError`` exception or returns the clean
  17. value:
  18. .. code-block:: pycon
  19. >>> from django import forms
  20. >>> f = forms.EmailField()
  21. >>> f.clean("foo@example.com")
  22. 'foo@example.com'
  23. >>> f.clean("invalid email address")
  24. Traceback (most recent call last):
  25. ...
  26. ValidationError: ['Enter a valid email address.']
  27. .. _core-field-arguments:
  28. Core field arguments
  29. ====================
  30. Each ``Field`` class constructor takes at least these arguments. Some
  31. ``Field`` classes take additional, field-specific arguments, but the following
  32. should *always* be accepted:
  33. ``required``
  34. ------------
  35. .. attribute:: Field.required
  36. By default, each ``Field`` class assumes the value is required, so if you pass
  37. an empty value -- either ``None`` or the empty string (``""``) -- then
  38. ``clean()`` will raise a ``ValidationError`` exception:
  39. .. code-block:: pycon
  40. >>> from django import forms
  41. >>> f = forms.CharField()
  42. >>> f.clean("foo")
  43. 'foo'
  44. >>> f.clean("")
  45. Traceback (most recent call last):
  46. ...
  47. ValidationError: ['This field is required.']
  48. >>> f.clean(None)
  49. Traceback (most recent call last):
  50. ...
  51. ValidationError: ['This field is required.']
  52. >>> f.clean(" ")
  53. ' '
  54. >>> f.clean(0)
  55. '0'
  56. >>> f.clean(True)
  57. 'True'
  58. >>> f.clean(False)
  59. 'False'
  60. To specify that a field is *not* required, pass ``required=False`` to the
  61. ``Field`` constructor:
  62. .. code-block:: pycon
  63. >>> f = forms.CharField(required=False)
  64. >>> f.clean("foo")
  65. 'foo'
  66. >>> f.clean("")
  67. ''
  68. >>> f.clean(None)
  69. ''
  70. >>> f.clean(0)
  71. '0'
  72. >>> f.clean(True)
  73. 'True'
  74. >>> f.clean(False)
  75. 'False'
  76. If a ``Field`` has ``required=False`` and you pass ``clean()`` an empty value,
  77. then ``clean()`` will return a *normalized* empty value rather than raising
  78. ``ValidationError``. For ``CharField``, this will return
  79. :attr:`~CharField.empty_value` which defaults to an empty string. For other
  80. ``Field`` classes, it might be ``None``. (This varies from field to field.)
  81. Widgets of required form fields have the ``required`` HTML attribute. Set the
  82. :attr:`Form.use_required_attribute` attribute to ``False`` to disable it. The
  83. ``required`` attribute isn't included on forms of formsets because the browser
  84. validation may not be correct when adding and deleting formsets.
  85. ``label``
  86. ---------
  87. .. attribute:: Field.label
  88. The ``label`` argument lets you specify the "human-friendly" label for this
  89. field. This is used when the ``Field`` is displayed in a ``Form``.
  90. As explained in "Outputting forms as HTML" above, the default label for a
  91. ``Field`` is generated from the field name by converting all underscores to
  92. spaces and upper-casing the first letter. Specify ``label`` if that default
  93. behavior doesn't result in an adequate label.
  94. Here's a full example ``Form`` that implements ``label`` for two of its fields.
  95. We've specified ``auto_id=False`` to simplify the output:
  96. .. code-block:: pycon
  97. >>> from django import forms
  98. >>> class CommentForm(forms.Form):
  99. ... name = forms.CharField(label="Your name")
  100. ... url = forms.URLField(label="Your website", required=False)
  101. ... comment = forms.CharField()
  102. ...
  103. >>> f = CommentForm(auto_id=False)
  104. >>> print(f)
  105. <div>Your name:<input type="text" name="name" required></div>
  106. <div>Your website:<input type="url" name="url"></div>
  107. <div>Comment:<input type="text" name="comment" required></div>
  108. ``label_suffix``
  109. ----------------
  110. .. attribute:: Field.label_suffix
  111. The ``label_suffix`` argument lets you override the form's
  112. :attr:`~django.forms.Form.label_suffix` on a per-field basis:
  113. .. code-block:: pycon
  114. >>> class ContactForm(forms.Form):
  115. ... age = forms.IntegerField()
  116. ... nationality = forms.CharField()
  117. ... captcha_answer = forms.IntegerField(label="2 + 2", label_suffix=" =")
  118. ...
  119. >>> f = ContactForm(label_suffix="?")
  120. >>> print(f)
  121. <div><label for="id_age">Age?</label><input type="number" name="age" required id="id_age"></div>
  122. <div><label for="id_nationality">Nationality?</label><input type="text" name="nationality" required id="id_nationality"></div>
  123. <div><label for="id_captcha_answer">2 + 2 =</label><input type="number" name="captcha_answer" required id="id_captcha_answer"></div>
  124. ``initial``
  125. -----------
  126. .. attribute:: Field.initial
  127. The ``initial`` argument lets you specify the initial value to use when
  128. rendering this ``Field`` in an unbound ``Form``.
  129. To specify dynamic initial data, see the :attr:`Form.initial` parameter.
  130. The use-case for this is when you want to display an "empty" form in which a
  131. field is initialized to a particular value. For example:
  132. .. code-block:: pycon
  133. >>> from django import forms
  134. >>> class CommentForm(forms.Form):
  135. ... name = forms.CharField(initial="Your name")
  136. ... url = forms.URLField(initial="http://")
  137. ... comment = forms.CharField()
  138. ...
  139. >>> f = CommentForm(auto_id=False)
  140. >>> print(f)
  141. <div>Name:<input type="text" name="name" value="Your name" required></div>
  142. <div>Url:<input type="url" name="url" value="http://" required></div>
  143. <div>Comment:<input type="text" name="comment" required></div>
  144. You may be thinking, why not just pass a dictionary of the initial values as
  145. data when displaying the form? Well, if you do that, you'll trigger validation,
  146. and the HTML output will include any validation errors:
  147. .. code-block:: pycon
  148. >>> class CommentForm(forms.Form):
  149. ... name = forms.CharField()
  150. ... url = forms.URLField()
  151. ... comment = forms.CharField()
  152. ...
  153. >>> default_data = {"name": "Your name", "url": "http://"}
  154. >>> f = CommentForm(default_data, auto_id=False)
  155. >>> print(f)
  156. <div>Name:<input type="text" name="name" value="Your name" required></div>
  157. <div>Url:<ul class="errorlist"><li>Enter a valid URL.</li></ul><input type="url" name="url" value="http://" required></div>
  158. <div>Comment:<ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="comment" required></div>
  159. This is why ``initial`` values are only displayed for unbound forms. For bound
  160. forms, the HTML output will use the bound data.
  161. Also note that ``initial`` values are *not* used as "fallback" data in
  162. validation if a particular field's value is not given. ``initial`` values are
  163. *only* intended for initial form display:
  164. .. code-block:: pycon
  165. >>> class CommentForm(forms.Form):
  166. ... name = forms.CharField(initial="Your name")
  167. ... url = forms.URLField(initial="http://")
  168. ... comment = forms.CharField()
  169. ...
  170. >>> data = {"name": "", "url": "", "comment": "Foo"}
  171. >>> f = CommentForm(data)
  172. >>> f.is_valid()
  173. False
  174. # The form does *not* fall back to using the initial values.
  175. >>> f.errors
  176. {'url': ['This field is required.'], 'name': ['This field is required.']}
  177. Instead of a constant, you can also pass any callable:
  178. .. code-block:: pycon
  179. >>> import datetime
  180. >>> class DateForm(forms.Form):
  181. ... day = forms.DateField(initial=datetime.date.today)
  182. ...
  183. >>> print(DateForm())
  184. <div><label for="id_day">Day:</label><input type="text" name="day" value="2023-02-11" required id="id_day"></div>
  185. The callable will be evaluated only when the unbound form is displayed, not when it is defined.
  186. ``widget``
  187. ----------
  188. .. attribute:: Field.widget
  189. The ``widget`` argument lets you specify a ``Widget`` class to use when
  190. rendering this ``Field``. See :doc:`/ref/forms/widgets` for more information.
  191. ``help_text``
  192. -------------
  193. .. attribute:: Field.help_text
  194. The ``help_text`` argument lets you specify descriptive text for this
  195. ``Field``. If you provide ``help_text``, it will be displayed next to the
  196. ``Field`` when the ``Field`` is rendered by one of the convenience ``Form``
  197. methods (e.g., ``as_ul()``).
  198. Like the model field's :attr:`~django.db.models.Field.help_text`, this value
  199. isn't HTML-escaped in automatically-generated forms.
  200. Here's a full example ``Form`` that implements ``help_text`` for two of its
  201. fields. We've specified ``auto_id=False`` to simplify the output:
  202. .. code-block:: pycon
  203. >>> from django import forms
  204. >>> class HelpTextContactForm(forms.Form):
  205. ... subject = forms.CharField(max_length=100, help_text="100 characters max.")
  206. ... message = forms.CharField()
  207. ... sender = forms.EmailField(help_text="A valid email address, please.")
  208. ... cc_myself = forms.BooleanField(required=False)
  209. ...
  210. >>> f = HelpTextContactForm(auto_id=False)
  211. >>> print(f)
  212. <div>Subject:<div class="helptext">100 characters max.</div><input type="text" name="subject" maxlength="100" required></div>
  213. <div>Message:<input type="text" name="message" required></div>
  214. <div>Sender:<div class="helptext">A valid email address, please.</div><input type="email" name="sender" required></div>
  215. <div>Cc myself:<input type="checkbox" name="cc_myself"></div>
  216. When a field has help text and :attr:`~django.forms.BoundField.id_for_label`
  217. returns a value, we associate ``help_text`` with the input using the
  218. ``aria-describedby`` HTML attribute:
  219. .. code-block:: pycon
  220. >>> from django import forms
  221. >>> class UserForm(forms.Form):
  222. ... username = forms.CharField(max_length=255, help_text="e.g., user@example.com")
  223. ...
  224. >>> f = UserForm()
  225. >>> print(f)
  226. <div>
  227. <label for="id_username">Username:</label>
  228. <div class="helptext" id="id_username_helptext">e.g., user@example.com</div>
  229. <input type="text" name="username" maxlength="255" required aria-describedby="id_username_helptext" id="id_username">
  230. </div>
  231. When adding a custom ``aria-describedby`` attribute, make sure to also include
  232. the ``id`` of the ``help_text`` element (if used) in the desired order. For
  233. screen reader users, descriptions will be read in their order of appearance
  234. inside ``aria-describedby``:
  235. .. code-block:: pycon
  236. >>> class UserForm(forms.Form):
  237. ... username = forms.CharField(
  238. ... max_length=255,
  239. ... help_text="e.g., user@example.com",
  240. ... widget=forms.TextInput(
  241. ... attrs={"aria-describedby": "custom-description id_username_helptext"},
  242. ... ),
  243. ... )
  244. ...
  245. >>> f = UserForm()
  246. >>> print(f["username"])
  247. <input type="text" name="username" aria-describedby="custom-description id_username_helptext" maxlength="255" id="id_username" required>
  248. .. versionchanged:: 5.0
  249. ``aria-describedby`` was added to associate ``help_text`` with its input.
  250. ``error_messages``
  251. ------------------
  252. .. attribute:: Field.error_messages
  253. The ``error_messages`` argument lets you override the default messages that the
  254. field will raise. Pass in a dictionary with keys matching the error messages you
  255. want to override. For example, here is the default error message:
  256. .. code-block:: pycon
  257. >>> from django import forms
  258. >>> generic = forms.CharField()
  259. >>> generic.clean("")
  260. Traceback (most recent call last):
  261. ...
  262. ValidationError: ['This field is required.']
  263. And here is a custom error message:
  264. .. code-block:: pycon
  265. >>> name = forms.CharField(error_messages={"required": "Please enter your name"})
  266. >>> name.clean("")
  267. Traceback (most recent call last):
  268. ...
  269. ValidationError: ['Please enter your name']
  270. In the `built-in Field classes`_ section below, each ``Field`` defines the
  271. error message keys it uses.
  272. ``validators``
  273. --------------
  274. .. attribute:: Field.validators
  275. The ``validators`` argument lets you provide a list of validation functions
  276. for this field.
  277. See the :doc:`validators documentation </ref/validators>` for more information.
  278. ``localize``
  279. ------------
  280. .. attribute:: Field.localize
  281. The ``localize`` argument enables the localization of form data input, as well
  282. as the rendered output.
  283. See the :doc:`format localization </topics/i18n/formatting>` documentation for
  284. more information.
  285. ``disabled``
  286. ------------
  287. .. attribute:: Field.disabled
  288. The ``disabled`` boolean argument, when set to ``True``, disables a form field
  289. using the ``disabled`` HTML attribute so that it won't be editable by users.
  290. Even if a user tampers with the field's value submitted to the server, it will
  291. be ignored in favor of the value from the form's initial data.
  292. ``template_name``
  293. -----------------
  294. .. attribute:: Field.template_name
  295. .. versionadded:: 5.0
  296. The ``template_name`` argument allows a custom template to be used when the
  297. field is rendered with :meth:`~django.forms.BoundField.as_field_group`. By
  298. default this value is set to ``"django/forms/field.html"``. Can be changed per
  299. field by overriding this attribute or more generally by overriding the default
  300. template, see also :ref:`overriding-built-in-field-templates`.
  301. Checking if the field data has changed
  302. ======================================
  303. ``has_changed()``
  304. -----------------
  305. .. method:: Field.has_changed()
  306. The ``has_changed()`` method is used to determine if the field value has changed
  307. from the initial value. Returns ``True`` or ``False``.
  308. See the :class:`Form.has_changed()` documentation for more information.
  309. .. _built-in-fields:
  310. Built-in ``Field`` classes
  311. ==========================
  312. Naturally, the ``forms`` library comes with a set of ``Field`` classes that
  313. represent common validation needs. This section documents each built-in field.
  314. For each field, we describe the default widget used if you don't specify
  315. ``widget``. We also specify the value returned when you provide an empty value
  316. (see the section on ``required`` above to understand what that means).
  317. ``BooleanField``
  318. ----------------
  319. .. class:: BooleanField(**kwargs)
  320. * Default widget: :class:`CheckboxInput`
  321. * Empty value: ``False``
  322. * Normalizes to: A Python ``True`` or ``False`` value.
  323. * Validates that the value is ``True`` (e.g. the check box is checked) if
  324. the field has ``required=True``.
  325. * Error message keys: ``required``
  326. .. note::
  327. Since all ``Field`` subclasses have ``required=True`` by default, the
  328. validation condition here is important. If you want to include a boolean
  329. in your form that can be either ``True`` or ``False`` (e.g. a checked or
  330. unchecked checkbox), you must remember to pass in ``required=False`` when
  331. creating the ``BooleanField``.
  332. ``CharField``
  333. -------------
  334. .. class:: CharField(**kwargs)
  335. * Default widget: :class:`TextInput`
  336. * Empty value: Whatever you've given as :attr:`empty_value`.
  337. * Normalizes to: A string.
  338. * Uses :class:`~django.core.validators.MaxLengthValidator` and
  339. :class:`~django.core.validators.MinLengthValidator` if ``max_length`` and
  340. ``min_length`` are provided. Otherwise, all inputs are valid.
  341. * Error message keys: ``required``, ``max_length``, ``min_length``
  342. Has the following optional arguments for validation:
  343. .. attribute:: max_length
  344. .. attribute:: min_length
  345. If provided, these arguments ensure that the string is at most or at
  346. least the given length.
  347. .. attribute:: strip
  348. If ``True`` (default), the value will be stripped of leading and
  349. trailing whitespace.
  350. .. attribute:: empty_value
  351. The value to use to represent "empty". Defaults to an empty string.
  352. ``ChoiceField``
  353. ---------------
  354. .. class:: ChoiceField(**kwargs)
  355. * Default widget: :class:`Select`
  356. * Empty value: ``''`` (an empty string)
  357. * Normalizes to: A string.
  358. * Validates that the given value exists in the list of choices.
  359. * Error message keys: ``required``, ``invalid_choice``
  360. The ``invalid_choice`` error message may contain ``%(value)s``, which will be
  361. replaced with the selected choice.
  362. Takes one extra argument:
  363. .. attribute:: choices
  364. Either an :term:`iterable` of 2-tuples to use as choices for this
  365. field, :ref:`enumeration type <field-choices-enum-types>`, or a
  366. callable that returns such an iterable. This argument accepts the same
  367. formats as the ``choices`` argument to a model field. See the
  368. :ref:`model field reference documentation on choices <field-choices>`
  369. for more details. If the argument is a callable, it is evaluated each
  370. time the field's form is initialized, in addition to during rendering.
  371. Defaults to an empty list.
  372. .. admonition:: Choice type
  373. This field normalizes choices to strings, so if choices are required in
  374. other data types, such as integers or booleans, consider using
  375. :class:`TypedChoiceField` instead.
  376. .. versionchanged:: 5.0
  377. Support for using :ref:`enumeration types <field-choices-enum-types>`
  378. directly in the ``choices`` was added.
  379. ``DateField``
  380. -------------
  381. .. class:: DateField(**kwargs)
  382. * Default widget: :class:`DateInput`
  383. * Empty value: ``None``
  384. * Normalizes to: A Python ``datetime.date`` object.
  385. * Validates that the given value is either a ``datetime.date``,
  386. ``datetime.datetime`` or string formatted in a particular date format.
  387. * Error message keys: ``required``, ``invalid``
  388. Takes one optional argument:
  389. .. attribute:: input_formats
  390. An iterable of formats used to attempt to convert a string to a valid
  391. ``datetime.date`` object.
  392. If no ``input_formats`` argument is provided, the default input formats are
  393. taken from the active locale format ``DATE_INPUT_FORMATS`` key, or from
  394. :setting:`DATE_INPUT_FORMATS` if localization is disabled. See also
  395. :doc:`format localization </topics/i18n/formatting>`.
  396. ``DateTimeField``
  397. -----------------
  398. .. class:: DateTimeField(**kwargs)
  399. * Default widget: :class:`DateTimeInput`
  400. * Empty value: ``None``
  401. * Normalizes to: A Python ``datetime.datetime`` object.
  402. * Validates that the given value is either a ``datetime.datetime``,
  403. ``datetime.date`` or string formatted in a particular datetime format.
  404. * Error message keys: ``required``, ``invalid``
  405. Takes one optional argument:
  406. .. attribute:: input_formats
  407. An iterable of formats used to attempt to convert a string to a valid
  408. ``datetime.datetime`` object, in addition to ISO 8601 formats.
  409. The field always accepts strings in ISO 8601 formatted dates or similar
  410. recognized by :func:`~django.utils.dateparse.parse_datetime`. Some examples
  411. are:
  412. * ``'2006-10-25 14:30:59'``
  413. * ``'2006-10-25T14:30:59'``
  414. * ``'2006-10-25 14:30'``
  415. * ``'2006-10-25T14:30'``
  416. * ``'2006-10-25T14:30Z'``
  417. * ``'2006-10-25T14:30+02:00'``
  418. * ``'2006-10-25'``
  419. If no ``input_formats`` argument is provided, the default input formats are
  420. taken from the active locale format ``DATETIME_INPUT_FORMATS`` and
  421. ``DATE_INPUT_FORMATS`` keys, or from :setting:`DATETIME_INPUT_FORMATS` and
  422. :setting:`DATE_INPUT_FORMATS` if localization is disabled. See also
  423. :doc:`format localization </topics/i18n/formatting>`.
  424. ``DecimalField``
  425. ----------------
  426. .. class:: DecimalField(**kwargs)
  427. * Default widget: :class:`NumberInput` when :attr:`Field.localize` is
  428. ``False``, else :class:`TextInput`.
  429. * Empty value: ``None``
  430. * Normalizes to: A Python ``decimal``.
  431. * Validates that the given value is a decimal. Uses
  432. :class:`~django.core.validators.MaxValueValidator` and
  433. :class:`~django.core.validators.MinValueValidator` if ``max_value`` and
  434. ``min_value`` are provided. Uses
  435. :class:`~django.core.validators.StepValueValidator` if ``step_size`` is
  436. provided. Leading and trailing whitespace is ignored.
  437. * Error message keys: ``required``, ``invalid``, ``max_value``,
  438. ``min_value``, ``max_digits``, ``max_decimal_places``,
  439. ``max_whole_digits``, ``step_size``.
  440. The ``max_value`` and ``min_value`` error messages may contain
  441. ``%(limit_value)s``, which will be substituted by the appropriate limit.
  442. Similarly, the ``max_digits``, ``max_decimal_places`` and
  443. ``max_whole_digits`` error messages may contain ``%(max)s``.
  444. Takes five optional arguments:
  445. .. attribute:: max_value
  446. .. attribute:: min_value
  447. These control the range of values permitted in the field, and should be
  448. given as ``decimal.Decimal`` values.
  449. .. attribute:: max_digits
  450. The maximum number of digits (those before the decimal point plus those
  451. after the decimal point, with leading zeros stripped) permitted in the
  452. value.
  453. .. attribute:: decimal_places
  454. The maximum number of decimal places permitted.
  455. .. attribute:: step_size
  456. Limit valid inputs to an integral multiple of ``step_size``. If
  457. ``min_value`` is also provided, it's added as an offset to determine if
  458. the step size matches.
  459. ``DurationField``
  460. -----------------
  461. .. class:: DurationField(**kwargs)
  462. * Default widget: :class:`TextInput`
  463. * Empty value: ``None``
  464. * Normalizes to: A Python :class:`~python:datetime.timedelta`.
  465. * Validates that the given value is a string which can be converted into a
  466. ``timedelta``. The value must be between :attr:`datetime.timedelta.min`
  467. and :attr:`datetime.timedelta.max`.
  468. * Error message keys: ``required``, ``invalid``, ``overflow``.
  469. Accepts any format understood by
  470. :func:`~django.utils.dateparse.parse_duration`.
  471. ``EmailField``
  472. --------------
  473. .. class:: EmailField(**kwargs)
  474. * Default widget: :class:`EmailInput`
  475. * Empty value: Whatever you've given as ``empty_value``.
  476. * Normalizes to: A string.
  477. * Uses :class:`~django.core.validators.EmailValidator` to validate that
  478. the given value is a valid email address, using a moderately complex
  479. regular expression.
  480. * Error message keys: ``required``, ``invalid``
  481. Has the optional arguments ``max_length``, ``min_length``, and
  482. ``empty_value`` which work just as they do for :class:`CharField`. The
  483. ``max_length`` argument defaults to 320 (see :rfc:`3696#section-3`).
  484. .. versionchanged:: 3.2.20
  485. The default value for ``max_length`` was changed to 320 characters.
  486. ``FileField``
  487. -------------
  488. .. class:: FileField(**kwargs)
  489. * Default widget: :class:`ClearableFileInput`
  490. * Empty value: ``None``
  491. * Normalizes to: An ``UploadedFile`` object that wraps the file content
  492. and file name into a single object.
  493. * Can validate that non-empty file data has been bound to the form.
  494. * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,
  495. ``max_length``
  496. Has the optional arguments for validation: ``max_length`` and
  497. ``allow_empty_file``. If provided, these ensure that the file name is at
  498. most the given length, and that validation will succeed even if the file
  499. content is empty.
  500. To learn more about the ``UploadedFile`` object, see the :doc:`file uploads
  501. documentation </topics/http/file-uploads>`.
  502. When you use a ``FileField`` in a form, you must also remember to
  503. :ref:`bind the file data to the form <binding-uploaded-files>`.
  504. The ``max_length`` error refers to the length of the filename. In the error
  505. message for that key, ``%(max)d`` will be replaced with the maximum filename
  506. length and ``%(length)d`` will be replaced with the current filename length.
  507. ``FilePathField``
  508. -----------------
  509. .. class:: FilePathField(**kwargs)
  510. * Default widget: :class:`Select`
  511. * Empty value: ``''`` (an empty string)
  512. * Normalizes to: A string.
  513. * Validates that the selected choice exists in the list of choices.
  514. * Error message keys: ``required``, ``invalid_choice``
  515. The field allows choosing from files inside a certain directory. It takes five
  516. extra arguments; only ``path`` is required:
  517. .. attribute:: path
  518. The absolute path to the directory whose contents you want listed. This
  519. directory must exist.
  520. .. attribute:: recursive
  521. If ``False`` (the default) only the direct contents of ``path`` will be
  522. offered as choices. If ``True``, the directory will be descended into
  523. recursively and all descendants will be listed as choices.
  524. .. attribute:: match
  525. A regular expression pattern; only files with names matching this expression
  526. will be allowed as choices.
  527. .. attribute:: allow_files
  528. Optional. Either ``True`` or ``False``. Default is ``True``. Specifies
  529. whether files in the specified location should be included. Either this or
  530. :attr:`allow_folders` must be ``True``.
  531. .. attribute:: allow_folders
  532. Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
  533. whether folders in the specified location should be included. Either this or
  534. :attr:`allow_files` must be ``True``.
  535. ``FloatField``
  536. --------------
  537. .. class:: FloatField(**kwargs)
  538. * Default widget: :class:`NumberInput` when :attr:`Field.localize` is
  539. ``False``, else :class:`TextInput`.
  540. * Empty value: ``None``
  541. * Normalizes to: A Python float.
  542. * Validates that the given value is a float. Uses
  543. :class:`~django.core.validators.MaxValueValidator` and
  544. :class:`~django.core.validators.MinValueValidator` if ``max_value`` and
  545. ``min_value`` are provided. Uses
  546. :class:`~django.core.validators.StepValueValidator` if ``step_size`` is
  547. provided. Leading and trailing whitespace is allowed, as in Python's
  548. ``float()`` function.
  549. * Error message keys: ``required``, ``invalid``, ``max_value``,
  550. ``min_value``, ``step_size``.
  551. Takes three optional arguments:
  552. .. attribute:: max_value
  553. .. attribute:: min_value
  554. These control the range of values permitted in the field.
  555. .. attribute:: step_size
  556. Limit valid inputs to an integral multiple of ``step_size``. If
  557. ``min_value`` is also provided, it's added as an offset to determine if
  558. the step size matches.
  559. ``GenericIPAddressField``
  560. -------------------------
  561. .. class:: GenericIPAddressField(**kwargs)
  562. A field containing either an IPv4 or an IPv6 address.
  563. * Default widget: :class:`TextInput`
  564. * Empty value: ``''`` (an empty string)
  565. * Normalizes to: A string. IPv6 addresses are normalized as described below.
  566. * Validates that the given value is a valid IP address.
  567. * Error message keys: ``required``, ``invalid``
  568. The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2,
  569. including using the IPv4 format suggested in paragraph 3 of that section, like
  570. ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to
  571. ``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters
  572. are converted to lowercase.
  573. Takes two optional arguments:
  574. .. attribute:: protocol
  575. Limits valid inputs to the specified protocol.
  576. Accepted values are ``both`` (default), ``IPv4``
  577. or ``IPv6``. Matching is case insensitive.
  578. .. attribute:: unpack_ipv4
  579. Unpacks IPv4 mapped addresses like ``::ffff:192.0.2.1``.
  580. If this option is enabled that address would be unpacked to
  581. ``192.0.2.1``. Default is disabled. Can only be used
  582. when ``protocol`` is set to ``'both'``.
  583. ``ImageField``
  584. --------------
  585. .. class:: ImageField(**kwargs)
  586. * Default widget: :class:`ClearableFileInput`
  587. * Empty value: ``None``
  588. * Normalizes to: An ``UploadedFile`` object that wraps the file content
  589. and file name into a single object.
  590. * Validates that file data has been bound to the form. Also uses
  591. :class:`~django.core.validators.FileExtensionValidator` to validate that
  592. the file extension is supported by Pillow.
  593. * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,
  594. ``invalid_image``
  595. Using an ``ImageField`` requires that `Pillow`_ is installed with support
  596. for the image formats you use. If you encounter a ``corrupt image`` error
  597. when you upload an image, it usually means that Pillow doesn't understand
  598. its format. To fix this, install the appropriate library and reinstall
  599. Pillow.
  600. When you use an ``ImageField`` on a form, you must also remember to
  601. :ref:`bind the file data to the form <binding-uploaded-files>`.
  602. After the field has been cleaned and validated, the ``UploadedFile``
  603. object will have an additional ``image`` attribute containing the Pillow
  604. `Image`_ instance used to check if the file was a valid image. Pillow
  605. closes the underlying file descriptor after verifying an image, so while
  606. non-image data attributes, such as ``format``, ``height``, and ``width``,
  607. are available, methods that access the underlying image data, such as
  608. ``getdata()`` or ``getpixel()``, cannot be used without reopening the file.
  609. For example:
  610. .. code-block:: pycon
  611. >>> from PIL import Image
  612. >>> from django import forms
  613. >>> from django.core.files.uploadedfile import SimpleUploadedFile
  614. >>> class ImageForm(forms.Form):
  615. ... img = forms.ImageField()
  616. ...
  617. >>> file_data = {"img": SimpleUploadedFile("test.png", b"file data")}
  618. >>> form = ImageForm({}, file_data)
  619. # Pillow closes the underlying file descriptor.
  620. >>> form.is_valid()
  621. True
  622. >>> image_field = form.cleaned_data["img"]
  623. >>> image_field.image
  624. <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=191x287 at 0x7F5985045C18>
  625. >>> image_field.image.width
  626. 191
  627. >>> image_field.image.height
  628. 287
  629. >>> image_field.image.format
  630. 'PNG'
  631. >>> image_field.image.getdata()
  632. # Raises AttributeError: 'NoneType' object has no attribute 'seek'.
  633. >>> image = Image.open(image_field)
  634. >>> image.getdata()
  635. <ImagingCore object at 0x7f5984f874b0>
  636. Additionally, ``UploadedFile.content_type`` will be updated with the
  637. image's content type if Pillow can determine it, otherwise it will be set
  638. to ``None``.
  639. .. _Pillow: https://pillow.readthedocs.io/en/latest/
  640. .. _Image: https://pillow.readthedocs.io/en/latest/reference/Image.html
  641. ``IntegerField``
  642. ----------------
  643. .. class:: IntegerField(**kwargs)
  644. * Default widget: :class:`NumberInput` when :attr:`Field.localize` is
  645. ``False``, else :class:`TextInput`.
  646. * Empty value: ``None``
  647. * Normalizes to: A Python integer.
  648. * Validates that the given value is an integer. Uses
  649. :class:`~django.core.validators.MaxValueValidator` and
  650. :class:`~django.core.validators.MinValueValidator` if ``max_value`` and
  651. ``min_value`` are provided. Uses
  652. :class:`~django.core.validators.StepValueValidator` if ``step_size`` is
  653. provided. Leading and trailing whitespace is allowed, as in Python's
  654. ``int()`` function.
  655. * Error message keys: ``required``, ``invalid``, ``max_value``,
  656. ``min_value``, ``step_size``
  657. The ``max_value``, ``min_value`` and ``step_size`` error messages may
  658. contain ``%(limit_value)s``, which will be substituted by the appropriate
  659. limit.
  660. Takes three optional arguments for validation:
  661. .. attribute:: max_value
  662. .. attribute:: min_value
  663. These control the range of values permitted in the field.
  664. .. attribute:: step_size
  665. Limit valid inputs to an integral multiple of ``step_size``. If
  666. ``min_value`` is also provided, it's added as an offset to determine if
  667. the step size matches.
  668. ``JSONField``
  669. -------------
  670. .. class:: JSONField(encoder=None, decoder=None, **kwargs)
  671. A field which accepts JSON encoded data for a
  672. :class:`~django.db.models.JSONField`.
  673. * Default widget: :class:`Textarea`
  674. * Empty value: ``None``
  675. * Normalizes to: A Python representation of the JSON value (usually as a
  676. ``dict``, ``list``, or ``None``), depending on :attr:`JSONField.decoder`.
  677. * Validates that the given value is a valid JSON.
  678. * Error message keys: ``required``, ``invalid``
  679. Takes two optional arguments:
  680. .. attribute:: encoder
  681. A :py:class:`json.JSONEncoder` subclass to serialize data types not
  682. supported by the standard JSON serializer (e.g. ``datetime.datetime``
  683. or :class:`~python:uuid.UUID`). For example, you can use the
  684. :class:`~django.core.serializers.json.DjangoJSONEncoder` class.
  685. Defaults to ``json.JSONEncoder``.
  686. .. attribute:: decoder
  687. A :py:class:`json.JSONDecoder` subclass to deserialize the input. Your
  688. deserialization may need to account for the fact that you can't be
  689. certain of the input type. For example, you run the risk of returning a
  690. ``datetime`` that was actually a string that just happened to be in the
  691. same format chosen for ``datetime``\s.
  692. The ``decoder`` can be used to validate the input. If
  693. :py:class:`json.JSONDecodeError` is raised during the deserialization,
  694. a ``ValidationError`` will be raised.
  695. Defaults to ``json.JSONDecoder``.
  696. .. note::
  697. If you use a :class:`ModelForm <django.forms.ModelForm>`, the
  698. ``encoder`` and ``decoder`` from :class:`~django.db.models.JSONField`
  699. will be used.
  700. .. admonition:: User friendly forms
  701. ``JSONField`` is not particularly user friendly in most cases. However,
  702. it is a useful way to format data from a client-side widget for
  703. submission to the server.
  704. ``MultipleChoiceField``
  705. -----------------------
  706. .. class:: MultipleChoiceField(**kwargs)
  707. * Default widget: :class:`SelectMultiple`
  708. * Empty value: ``[]`` (an empty list)
  709. * Normalizes to: A list of strings.
  710. * Validates that every value in the given list of values exists in the list
  711. of choices.
  712. * Error message keys: ``required``, ``invalid_choice``, ``invalid_list``
  713. The ``invalid_choice`` error message may contain ``%(value)s``, which will be
  714. replaced with the selected choice.
  715. Takes one extra required argument, ``choices``, as for :class:`ChoiceField`.
  716. ``NullBooleanField``
  717. --------------------
  718. .. class:: NullBooleanField(**kwargs)
  719. * Default widget: :class:`NullBooleanSelect`
  720. * Empty value: ``None``
  721. * Normalizes to: A Python ``True``, ``False`` or ``None`` value.
  722. * Validates nothing (i.e., it never raises a ``ValidationError``).
  723. ``NullBooleanField`` may be used with widgets such as
  724. :class:`~django.forms.Select` or :class:`~django.forms.RadioSelect`
  725. by providing the widget ``choices``::
  726. NullBooleanField(
  727. widget=Select(
  728. choices=[
  729. ("", "Unknown"),
  730. (True, "Yes"),
  731. (False, "No"),
  732. ]
  733. )
  734. )
  735. ``RegexField``
  736. --------------
  737. .. class:: RegexField(**kwargs)
  738. * Default widget: :class:`TextInput`
  739. * Empty value: Whatever you've given as ``empty_value``.
  740. * Normalizes to: A string.
  741. * Uses :class:`~django.core.validators.RegexValidator` to validate that
  742. the given value matches a certain regular expression.
  743. * Error message keys: ``required``, ``invalid``
  744. Takes one required argument:
  745. .. attribute:: regex
  746. A regular expression specified either as a string or a compiled regular
  747. expression object.
  748. Also takes ``max_length``, ``min_length``, ``strip``, and ``empty_value``
  749. which work just as they do for :class:`CharField`.
  750. .. attribute:: strip
  751. Defaults to ``False``. If enabled, stripping will be applied before the
  752. regex validation.
  753. ``SlugField``
  754. -------------
  755. .. class:: SlugField(**kwargs)
  756. * Default widget: :class:`TextInput`
  757. * Empty value: Whatever you've given as :attr:`empty_value`.
  758. * Normalizes to: A string.
  759. * Uses :class:`~django.core.validators.validate_slug` or
  760. :class:`~django.core.validators.validate_unicode_slug` to validate that
  761. the given value contains only letters, numbers, underscores, and hyphens.
  762. * Error messages: ``required``, ``invalid``
  763. This field is intended for use in representing a model
  764. :class:`~django.db.models.SlugField` in forms.
  765. Takes two optional parameters:
  766. .. attribute:: allow_unicode
  767. A boolean instructing the field to accept Unicode letters in addition
  768. to ASCII letters. Defaults to ``False``.
  769. .. attribute:: empty_value
  770. The value to use to represent "empty". Defaults to an empty string.
  771. ``TimeField``
  772. -------------
  773. .. class:: TimeField(**kwargs)
  774. * Default widget: :class:`TimeInput`
  775. * Empty value: ``None``
  776. * Normalizes to: A Python ``datetime.time`` object.
  777. * Validates that the given value is either a ``datetime.time`` or string
  778. formatted in a particular time format.
  779. * Error message keys: ``required``, ``invalid``
  780. Takes one optional argument:
  781. .. attribute:: input_formats
  782. An iterable of formats used to attempt to convert a string to a valid
  783. ``datetime.time`` object.
  784. If no ``input_formats`` argument is provided, the default input formats are
  785. taken from the active locale format ``TIME_INPUT_FORMATS`` key, or from
  786. :setting:`TIME_INPUT_FORMATS` if localization is disabled. See also
  787. :doc:`format localization </topics/i18n/formatting>`.
  788. ``TypedChoiceField``
  789. --------------------
  790. .. class:: TypedChoiceField(**kwargs)
  791. Just like a :class:`ChoiceField`, except :class:`TypedChoiceField` takes two
  792. extra arguments, :attr:`coerce` and :attr:`empty_value`.
  793. * Default widget: :class:`Select`
  794. * Empty value: Whatever you've given as :attr:`empty_value`.
  795. * Normalizes to: A value of the type provided by the :attr:`coerce`
  796. argument.
  797. * Validates that the given value exists in the list of choices and can be
  798. coerced.
  799. * Error message keys: ``required``, ``invalid_choice``
  800. Takes extra arguments:
  801. .. attribute:: coerce
  802. A function that takes one argument and returns a coerced value. Examples
  803. include the built-in ``int``, ``float``, ``bool`` and other types. Defaults
  804. to an identity function. Note that coercion happens after input
  805. validation, so it is possible to coerce to a value not present in
  806. ``choices``.
  807. .. attribute:: empty_value
  808. The value to use to represent "empty." Defaults to the empty string;
  809. ``None`` is another common choice here. Note that this value will not be
  810. coerced by the function given in the ``coerce`` argument, so choose it
  811. accordingly.
  812. ``TypedMultipleChoiceField``
  813. ----------------------------
  814. .. class:: TypedMultipleChoiceField(**kwargs)
  815. Just like a :class:`MultipleChoiceField`, except :class:`TypedMultipleChoiceField`
  816. takes two extra arguments, ``coerce`` and ``empty_value``.
  817. * Default widget: :class:`SelectMultiple`
  818. * Empty value: Whatever you've given as ``empty_value``
  819. * Normalizes to: A list of values of the type provided by the ``coerce``
  820. argument.
  821. * Validates that the given values exists in the list of choices and can be
  822. coerced.
  823. * Error message keys: ``required``, ``invalid_choice``
  824. The ``invalid_choice`` error message may contain ``%(value)s``, which will be
  825. replaced with the selected choice.
  826. Takes two extra arguments, ``coerce`` and ``empty_value``, as for
  827. :class:`TypedChoiceField`.
  828. ``URLField``
  829. ------------
  830. .. class:: URLField(**kwargs)
  831. * Default widget: :class:`URLInput`
  832. * Empty value: Whatever you've given as ``empty_value``.
  833. * Normalizes to: A string.
  834. * Uses :class:`~django.core.validators.URLValidator` to validate that the
  835. given value is a valid URL.
  836. * Error message keys: ``required``, ``invalid``
  837. Has the optional arguments ``max_length``, ``min_length``, ``empty_value``
  838. which work just as they do for :class:`CharField`, and ``assume_scheme``
  839. that defaults to ``"http"``.
  840. .. versionchanged:: 5.0
  841. The ``assume_scheme`` argument was added.
  842. .. deprecated:: 5.0
  843. The default value for ``assume_scheme`` will change from ``"http"`` to
  844. ``"https"`` in Django 6.0.
  845. ``UUIDField``
  846. -------------
  847. .. class:: UUIDField(**kwargs)
  848. * Default widget: :class:`TextInput`
  849. * Empty value: ``None``
  850. * Normalizes to: A :class:`~python:uuid.UUID` object.
  851. * Error message keys: ``required``, ``invalid``
  852. This field will accept any string format accepted as the ``hex`` argument
  853. to the :class:`~python:uuid.UUID` constructor.
  854. Slightly complex built-in ``Field`` classes
  855. ===========================================
  856. ``ComboField``
  857. --------------
  858. .. class:: ComboField(**kwargs)
  859. * Default widget: :class:`TextInput`
  860. * Empty value: ``''`` (an empty string)
  861. * Normalizes to: A string.
  862. * Validates the given value against each of the fields specified
  863. as an argument to the ``ComboField``.
  864. * Error message keys: ``required``, ``invalid``
  865. Takes one extra required argument:
  866. .. attribute:: fields
  867. The list of fields that should be used to validate the field's value (in
  868. the order in which they are provided).
  869. >>> from django.forms import ComboField
  870. >>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
  871. >>> f.clean('test@example.com')
  872. 'test@example.com'
  873. >>> f.clean('longemailaddress@example.com')
  874. Traceback (most recent call last):
  875. ...
  876. ValidationError: ['Ensure this value has at most 20 characters (it has 28).']
  877. ``MultiValueField``
  878. -------------------
  879. .. class:: MultiValueField(fields=(), **kwargs)
  880. * Default widget: :class:`TextInput`
  881. * Empty value: ``''`` (an empty string)
  882. * Normalizes to: the type returned by the ``compress`` method of the subclass.
  883. * Validates the given value against each of the fields specified
  884. as an argument to the ``MultiValueField``.
  885. * Error message keys: ``required``, ``invalid``, ``incomplete``
  886. Aggregates the logic of multiple fields that together produce a single
  887. value.
  888. This field is abstract and must be subclassed. In contrast with the
  889. single-value fields, subclasses of :class:`MultiValueField` must not
  890. implement :meth:`~django.forms.Field.clean` but instead - implement
  891. :meth:`~MultiValueField.compress`.
  892. Takes one extra required argument:
  893. .. attribute:: fields
  894. A tuple of fields whose values are cleaned and subsequently combined
  895. into a single value. Each value of the field is cleaned by the
  896. corresponding field in ``fields`` -- the first value is cleaned by the
  897. first field, the second value is cleaned by the second field, etc.
  898. Once all fields are cleaned, the list of clean values is combined into
  899. a single value by :meth:`~MultiValueField.compress`.
  900. Also takes some optional arguments:
  901. .. attribute:: require_all_fields
  902. Defaults to ``True``, in which case a ``required`` validation error
  903. will be raised if no value is supplied for any field.
  904. When set to ``False``, the :attr:`Field.required` attribute can be set
  905. to ``False`` for individual fields to make them optional. If no value
  906. is supplied for a required field, an ``incomplete`` validation error
  907. will be raised.
  908. A default ``incomplete`` error message can be defined on the
  909. :class:`MultiValueField` subclass, or different messages can be defined
  910. on each individual field. For example::
  911. from django.core.validators import RegexValidator
  912. class PhoneField(MultiValueField):
  913. def __init__(self, **kwargs):
  914. # Define one message for all fields.
  915. error_messages = {
  916. "incomplete": "Enter a country calling code and a phone number.",
  917. }
  918. # Or define a different message for each field.
  919. fields = (
  920. CharField(
  921. error_messages={"incomplete": "Enter a country calling code."},
  922. validators=[
  923. RegexValidator(r"^[0-9]+$", "Enter a valid country calling code."),
  924. ],
  925. ),
  926. CharField(
  927. error_messages={"incomplete": "Enter a phone number."},
  928. validators=[RegexValidator(r"^[0-9]+$", "Enter a valid phone number.")],
  929. ),
  930. CharField(
  931. validators=[RegexValidator(r"^[0-9]+$", "Enter a valid extension.")],
  932. required=False,
  933. ),
  934. )
  935. super().__init__(
  936. error_messages=error_messages,
  937. fields=fields,
  938. require_all_fields=False,
  939. **kwargs
  940. )
  941. .. attribute:: MultiValueField.widget
  942. Must be a subclass of :class:`django.forms.MultiWidget`.
  943. Default value is :class:`~django.forms.TextInput`, which
  944. probably is not very useful in this case.
  945. .. method:: compress(data_list)
  946. Takes a list of valid values and returns a "compressed" version of
  947. those values -- in a single value. For example,
  948. :class:`SplitDateTimeField` is a subclass which combines a time field
  949. and a date field into a ``datetime`` object.
  950. This method must be implemented in the subclasses.
  951. ``SplitDateTimeField``
  952. ----------------------
  953. .. class:: SplitDateTimeField(**kwargs)
  954. * Default widget: :class:`SplitDateTimeWidget`
  955. * Empty value: ``None``
  956. * Normalizes to: A Python ``datetime.datetime`` object.
  957. * Validates that the given value is a ``datetime.datetime`` or string
  958. formatted in a particular datetime format.
  959. * Error message keys: ``required``, ``invalid``, ``invalid_date``,
  960. ``invalid_time``
  961. Takes two optional arguments:
  962. .. attribute:: input_date_formats
  963. A list of formats used to attempt to convert a string to a valid
  964. ``datetime.date`` object.
  965. If no ``input_date_formats`` argument is provided, the default input formats
  966. for :class:`DateField` are used.
  967. .. attribute:: input_time_formats
  968. A list of formats used to attempt to convert a string to a valid
  969. ``datetime.time`` object.
  970. If no ``input_time_formats`` argument is provided, the default input formats
  971. for :class:`TimeField` are used.
  972. .. _fields-which-handle-relationships:
  973. Fields which handle relationships
  974. =================================
  975. Two fields are available for representing relationships between
  976. models: :class:`ModelChoiceField` and
  977. :class:`ModelMultipleChoiceField`. Both of these fields require a
  978. single ``queryset`` parameter that is used to create the choices for
  979. the field. Upon form validation, these fields will place either one
  980. model object (in the case of ``ModelChoiceField``) or multiple model
  981. objects (in the case of ``ModelMultipleChoiceField``) into the
  982. ``cleaned_data`` dictionary of the form.
  983. For more complex uses, you can specify ``queryset=None`` when declaring the
  984. form field and then populate the ``queryset`` in the form's ``__init__()``
  985. method::
  986. class FooMultipleChoiceForm(forms.Form):
  987. foo_select = forms.ModelMultipleChoiceField(queryset=None)
  988. def __init__(self, *args, **kwargs):
  989. super().__init__(*args, **kwargs)
  990. self.fields["foo_select"].queryset = ...
  991. Both ``ModelChoiceField`` and ``ModelMultipleChoiceField`` have an ``iterator``
  992. attribute which specifies the class used to iterate over the queryset when
  993. generating choices. See :ref:`iterating-relationship-choices` for details.
  994. ``ModelChoiceField``
  995. --------------------
  996. .. class:: ModelChoiceField(**kwargs)
  997. * Default widget: :class:`Select`
  998. * Empty value: ``None``
  999. * Normalizes to: A model instance.
  1000. * Validates that the given id exists in the queryset.
  1001. * Error message keys: ``required``, ``invalid_choice``
  1002. The ``invalid_choice`` error message may contain ``%(value)s``, which will
  1003. be replaced with the selected choice.
  1004. Allows the selection of a single model object, suitable for representing a
  1005. foreign key. Note that the default widget for ``ModelChoiceField`` becomes
  1006. impractical when the number of entries increases. You should avoid using it
  1007. for more than 100 items.
  1008. A single argument is required:
  1009. .. attribute:: queryset
  1010. A ``QuerySet`` of model objects from which the choices for the field
  1011. are derived and which is used to validate the user's selection. It's
  1012. evaluated when the form is rendered.
  1013. ``ModelChoiceField`` also takes several optional arguments:
  1014. .. attribute:: empty_label
  1015. By default the ``<select>`` widget used by ``ModelChoiceField`` will have an
  1016. empty choice at the top of the list. You can change the text of this
  1017. label (which is ``"---------"`` by default) with the ``empty_label``
  1018. attribute, or you can disable the empty label entirely by setting
  1019. ``empty_label`` to ``None``::
  1020. # A custom empty label
  1021. field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)")
  1022. # No empty label
  1023. field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
  1024. Note that no empty choice is created (regardless of the value of
  1025. ``empty_label``) if a ``ModelChoiceField`` is required and has a
  1026. default initial value, or a ``widget`` is set to
  1027. :class:`~django.forms.RadioSelect` and the
  1028. :attr:`~ModelChoiceField.blank` argument is ``False``.
  1029. .. attribute:: to_field_name
  1030. This optional argument is used to specify the field to use as the value
  1031. of the choices in the field's widget. Be sure it's a unique field for
  1032. the model, otherwise the selected value could match more than one
  1033. object. By default it is set to ``None``, in which case the primary key
  1034. of each object will be used. For example::
  1035. # No custom to_field_name
  1036. field1 = forms.ModelChoiceField(queryset=...)
  1037. would yield:
  1038. .. code-block:: html
  1039. <select id="id_field1" name="field1">
  1040. <option value="obj1.pk">Object1</option>
  1041. <option value="obj2.pk">Object2</option>
  1042. ...
  1043. </select>
  1044. and::
  1045. # to_field_name provided
  1046. field2 = forms.ModelChoiceField(queryset=..., to_field_name="name")
  1047. would yield:
  1048. .. code-block:: html
  1049. <select id="id_field2" name="field2">
  1050. <option value="obj1.name">Object1</option>
  1051. <option value="obj2.name">Object2</option>
  1052. ...
  1053. </select>
  1054. .. attribute:: blank
  1055. When using the :class:`~django.forms.RadioSelect` widget, this optional
  1056. boolean argument determines whether an empty choice is created. By
  1057. default, ``blank`` is ``False``, in which case no empty choice is
  1058. created.
  1059. ``ModelChoiceField`` also has the attribute:
  1060. .. attribute:: iterator
  1061. The iterator class used to generate field choices from ``queryset``. By
  1062. default, :class:`ModelChoiceIterator`.
  1063. The ``__str__()`` method of the model will be called to generate string
  1064. representations of the objects for use in the field's choices. To provide
  1065. customized representations, subclass ``ModelChoiceField`` and override
  1066. ``label_from_instance``. This method will receive a model object and should
  1067. return a string suitable for representing it. For example::
  1068. from django.forms import ModelChoiceField
  1069. class MyModelChoiceField(ModelChoiceField):
  1070. def label_from_instance(self, obj):
  1071. return "My Object #%i" % obj.id
  1072. ``ModelMultipleChoiceField``
  1073. ----------------------------
  1074. .. class:: ModelMultipleChoiceField(**kwargs)
  1075. * Default widget: :class:`SelectMultiple`
  1076. * Empty value: An empty ``QuerySet`` (``self.queryset.none()``)
  1077. * Normalizes to: A ``QuerySet`` of model instances.
  1078. * Validates that every id in the given list of values exists in the
  1079. queryset.
  1080. * Error message keys: ``required``, ``invalid_list``, ``invalid_choice``,
  1081. ``invalid_pk_value``
  1082. The ``invalid_choice`` message may contain ``%(value)s`` and the
  1083. ``invalid_pk_value`` message may contain ``%(pk)s``, which will be
  1084. substituted by the appropriate values.
  1085. Allows the selection of one or more model objects, suitable for
  1086. representing a many-to-many relation. As with :class:`ModelChoiceField`,
  1087. you can use ``label_from_instance`` to customize the object
  1088. representations.
  1089. A single argument is required:
  1090. .. attribute:: queryset
  1091. Same as :class:`ModelChoiceField.queryset`.
  1092. Takes one optional argument:
  1093. .. attribute:: to_field_name
  1094. Same as :class:`ModelChoiceField.to_field_name`.
  1095. ``ModelMultipleChoiceField`` also has the attribute:
  1096. .. attribute:: iterator
  1097. Same as :class:`ModelChoiceField.iterator`.
  1098. .. _iterating-relationship-choices:
  1099. Iterating relationship choices
  1100. ------------------------------
  1101. By default, :class:`ModelChoiceField` and :class:`ModelMultipleChoiceField` use
  1102. :class:`ModelChoiceIterator` to generate their field ``choices``.
  1103. When iterated, ``ModelChoiceIterator`` yields 2-tuple choices containing
  1104. :class:`ModelChoiceIteratorValue` instances as the first ``value`` element in
  1105. each choice. ``ModelChoiceIteratorValue`` wraps the choice value while
  1106. maintaining a reference to the source model instance that can be used in custom
  1107. widget implementations, for example, to add `data-* attributes`_ to
  1108. ``<option>`` elements.
  1109. .. _`data-* attributes`: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*
  1110. For example, consider the following models::
  1111. from django.db import models
  1112. class Topping(models.Model):
  1113. name = models.CharField(max_length=100)
  1114. price = models.DecimalField(decimal_places=2, max_digits=6)
  1115. def __str__(self):
  1116. return self.name
  1117. class Pizza(models.Model):
  1118. topping = models.ForeignKey(Topping, on_delete=models.CASCADE)
  1119. You can use a :class:`~django.forms.Select` widget subclass to include
  1120. the value of ``Topping.price`` as the HTML attribute ``data-price`` for each
  1121. ``<option>`` element::
  1122. from django import forms
  1123. class ToppingSelect(forms.Select):
  1124. def create_option(
  1125. self, name, value, label, selected, index, subindex=None, attrs=None
  1126. ):
  1127. option = super().create_option(
  1128. name, value, label, selected, index, subindex, attrs
  1129. )
  1130. if value:
  1131. option["attrs"]["data-price"] = value.instance.price
  1132. return option
  1133. class PizzaForm(forms.ModelForm):
  1134. class Meta:
  1135. model = Pizza
  1136. fields = ["topping"]
  1137. widgets = {"topping": ToppingSelect}
  1138. This will render the ``Pizza.topping`` select as:
  1139. .. code-block:: html
  1140. <select id="id_topping" name="topping" required>
  1141. <option value="" selected>---------</option>
  1142. <option value="1" data-price="1.50">mushrooms</option>
  1143. <option value="2" data-price="1.25">onions</option>
  1144. <option value="3" data-price="1.75">peppers</option>
  1145. <option value="4" data-price="2.00">pineapple</option>
  1146. </select>
  1147. For more advanced usage you may subclass ``ModelChoiceIterator`` in order to
  1148. customize the yielded 2-tuple choices.
  1149. ``ModelChoiceIterator``
  1150. ~~~~~~~~~~~~~~~~~~~~~~~
  1151. .. class:: ModelChoiceIterator(field)
  1152. The default class assigned to the ``iterator`` attribute of
  1153. :class:`ModelChoiceField` and :class:`ModelMultipleChoiceField`. An
  1154. iterable that yields 2-tuple choices from the queryset.
  1155. A single argument is required:
  1156. .. attribute:: field
  1157. The instance of ``ModelChoiceField`` or ``ModelMultipleChoiceField`` to
  1158. iterate and yield choices.
  1159. ``ModelChoiceIterator`` has the following method:
  1160. .. method:: __iter__()
  1161. Yields 2-tuple choices, in the ``(value, label)`` format used by
  1162. :attr:`ChoiceField.choices`. The first ``value`` element is a
  1163. :class:`ModelChoiceIteratorValue` instance.
  1164. ``ModelChoiceIteratorValue``
  1165. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1166. .. class:: ModelChoiceIteratorValue(value, instance)
  1167. Two arguments are required:
  1168. .. attribute:: value
  1169. The value of the choice. This value is used to render the ``value``
  1170. attribute of an HTML ``<option>`` element.
  1171. .. attribute:: instance
  1172. The model instance from the queryset. The instance can be accessed in
  1173. custom ``ChoiceWidget.create_option()`` implementations to adjust the
  1174. rendered HTML.
  1175. ``ModelChoiceIteratorValue`` has the following method:
  1176. .. method:: __str__()
  1177. Return ``value`` as a string to be rendered in HTML.
  1178. Creating custom fields
  1179. ======================
  1180. If the built-in ``Field`` classes don't meet your needs, you can create custom
  1181. ``Field`` classes. To do this, create a subclass of ``django.forms.Field``. Its
  1182. only requirements are that it implement a ``clean()`` method and that its
  1183. ``__init__()`` method accept the core arguments mentioned above (``required``,
  1184. ``label``, ``initial``, ``widget``, ``help_text``).
  1185. You can also customize how a field will be accessed by overriding
  1186. :meth:`~django.forms.Field.get_bound_field()`.