fields.txt 57 KB

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