fields.txt 58 KB

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