fields.txt 54 KB

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