fields.txt 54 KB

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