fields.txt 54 KB

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