fields.txt 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482
  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. ``RegexField``
  686. --------------
  687. .. class:: RegexField(**kwargs)
  688. * Default widget: :class:`TextInput`
  689. * Empty value: Whatever you've given as ``empty_value``.
  690. * Normalizes to: A string.
  691. * Uses :class:`~django.core.validators.RegexValidator` to validate that
  692. the given value matches a certain regular expression.
  693. * Error message keys: ``required``, ``invalid``
  694. Takes one required argument:
  695. .. attribute:: regex
  696. A regular expression specified either as a string or a compiled regular
  697. expression object.
  698. Also takes ``max_length``, ``min_length``, ``strip``, and ``empty_value``
  699. which work just as they do for :class:`CharField`.
  700. .. attribute:: strip
  701. Defaults to ``False``. If enabled, stripping will be applied before the
  702. regex validation.
  703. ``SlugField``
  704. -------------
  705. .. class:: SlugField(**kwargs)
  706. * Default widget: :class:`TextInput`
  707. * Empty value: Whatever you've given as :attr:`empty_value`.
  708. * Normalizes to: A string.
  709. * Uses :class:`~django.core.validators.validate_slug` or
  710. :class:`~django.core.validators.validate_unicode_slug` to validate that
  711. the given value contains only letters, numbers, underscores, and hyphens.
  712. * Error messages: ``required``, ``invalid``
  713. This field is intended for use in representing a model
  714. :class:`~django.db.models.SlugField` in forms.
  715. Takes two optional parameters:
  716. .. attribute:: allow_unicode
  717. A boolean instructing the field to accept Unicode letters in addition
  718. to ASCII letters. Defaults to ``False``.
  719. .. attribute:: empty_value
  720. The value to use to represent "empty". Defaults to an empty string.
  721. ``TimeField``
  722. -------------
  723. .. class:: TimeField(**kwargs)
  724. * Default widget: :class:`TimeInput`
  725. * Empty value: ``None``
  726. * Normalizes to: A Python ``datetime.time`` object.
  727. * Validates that the given value is either a ``datetime.time`` or string
  728. formatted in a particular time format.
  729. * Error message keys: ``required``, ``invalid``
  730. Takes one optional argument:
  731. .. attribute:: input_formats
  732. A list of formats used to attempt to convert a string to a valid
  733. ``datetime.time`` object.
  734. If no ``input_formats`` argument is provided, the default input formats are
  735. taken from :setting:`TIME_INPUT_FORMATS` if :setting:`USE_L10N` is
  736. ``False``, or from the active locale format ``TIME_INPUT_FORMATS`` key if
  737. localization is enabled. See also :doc:`format localization
  738. </topics/i18n/formatting>`.
  739. ``URLField``
  740. ------------
  741. .. class:: URLField(**kwargs)
  742. * Default widget: :class:`URLInput`
  743. * Empty value: Whatever you've given as ``empty_value``.
  744. * Normalizes to: A string.
  745. * Uses :class:`~django.core.validators.URLValidator` to validate that the
  746. given value is a valid URL.
  747. * Error message keys: ``required``, ``invalid``
  748. Has three optional arguments ``max_length``, ``min_length``, and
  749. ``empty_value`` which work just as they do for :class:`CharField`.
  750. ``UUIDField``
  751. -------------
  752. .. class:: UUIDField(**kwargs)
  753. * Default widget: :class:`TextInput`
  754. * Empty value: ``None``
  755. * Normalizes to: A :class:`~python:uuid.UUID` object.
  756. * Error message keys: ``required``, ``invalid``
  757. This field will accept any string format accepted as the ``hex`` argument
  758. to the :class:`~python:uuid.UUID` constructor.
  759. Slightly complex built-in ``Field`` classes
  760. ===========================================
  761. ``ComboField``
  762. --------------
  763. .. class:: ComboField(**kwargs)
  764. * Default widget: :class:`TextInput`
  765. * Empty value: ``''`` (an empty string)
  766. * Normalizes to: A string.
  767. * Validates the given value against each of the fields specified
  768. as an argument to the ``ComboField``.
  769. * Error message keys: ``required``, ``invalid``
  770. Takes one extra required argument:
  771. .. attribute:: fields
  772. The list of fields that should be used to validate the field's value (in
  773. the order in which they are provided).
  774. >>> from django.forms import ComboField
  775. >>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
  776. >>> f.clean('test@example.com')
  777. 'test@example.com'
  778. >>> f.clean('longemailaddress@example.com')
  779. Traceback (most recent call last):
  780. ...
  781. ValidationError: ['Ensure this value has at most 20 characters (it has 28).']
  782. ``MultiValueField``
  783. -------------------
  784. .. class:: MultiValueField(fields=(), **kwargs)
  785. * Default widget: :class:`TextInput`
  786. * Empty value: ``''`` (an empty string)
  787. * Normalizes to: the type returned by the ``compress`` method of the subclass.
  788. * Validates the given value against each of the fields specified
  789. as an argument to the ``MultiValueField``.
  790. * Error message keys: ``required``, ``invalid``, ``incomplete``
  791. Aggregates the logic of multiple fields that together produce a single
  792. value.
  793. This field is abstract and must be subclassed. In contrast with the
  794. single-value fields, subclasses of :class:`MultiValueField` must not
  795. implement :meth:`~django.forms.Field.clean` but instead - implement
  796. :meth:`~MultiValueField.compress`.
  797. Takes one extra required argument:
  798. .. attribute:: fields
  799. A tuple of fields whose values are cleaned and subsequently combined
  800. into a single value. Each value of the field is cleaned by the
  801. corresponding field in ``fields`` -- the first value is cleaned by the
  802. first field, the second value is cleaned by the second field, etc.
  803. Once all fields are cleaned, the list of clean values is combined into
  804. a single value by :meth:`~MultiValueField.compress`.
  805. Also takes some optional arguments:
  806. .. attribute:: require_all_fields
  807. Defaults to ``True``, in which case a ``required`` validation error
  808. will be raised if no value is supplied for any field.
  809. When set to ``False``, the :attr:`Field.required` attribute can be set
  810. to ``False`` for individual fields to make them optional. If no value
  811. is supplied for a required field, an ``incomplete`` validation error
  812. will be raised.
  813. A default ``incomplete`` error message can be defined on the
  814. :class:`MultiValueField` subclass, or different messages can be defined
  815. on each individual field. For example::
  816. from django.core.validators import RegexValidator
  817. class PhoneField(MultiValueField):
  818. def __init__(self, **kwargs):
  819. # Define one message for all fields.
  820. error_messages = {
  821. 'incomplete': 'Enter a country calling code and a phone number.',
  822. }
  823. # Or define a different message for each field.
  824. fields = (
  825. CharField(
  826. error_messages={'incomplete': 'Enter a country calling code.'},
  827. validators=[
  828. RegexValidator(r'^[0-9]+$', 'Enter a valid country calling code.'),
  829. ],
  830. ),
  831. CharField(
  832. error_messages={'incomplete': 'Enter a phone number.'},
  833. validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid phone number.')],
  834. ),
  835. CharField(
  836. validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid extension.')],
  837. required=False,
  838. ),
  839. )
  840. super().__init__(
  841. error_messages=error_messages, fields=fields,
  842. require_all_fields=False, **kwargs
  843. )
  844. .. attribute:: MultiValueField.widget
  845. Must be a subclass of :class:`django.forms.MultiWidget`.
  846. Default value is :class:`~django.forms.TextInput`, which
  847. probably is not very useful in this case.
  848. .. method:: compress(data_list)
  849. Takes a list of valid values and returns a "compressed" version of
  850. those values -- in a single value. For example,
  851. :class:`SplitDateTimeField` is a subclass which combines a time field
  852. and a date field into a ``datetime`` object.
  853. This method must be implemented in the subclasses.
  854. ``SplitDateTimeField``
  855. ----------------------
  856. .. class:: SplitDateTimeField(**kwargs)
  857. * Default widget: :class:`SplitDateTimeWidget`
  858. * Empty value: ``None``
  859. * Normalizes to: A Python ``datetime.datetime`` object.
  860. * Validates that the given value is a ``datetime.datetime`` or string
  861. formatted in a particular datetime format.
  862. * Error message keys: ``required``, ``invalid``, ``invalid_date``,
  863. ``invalid_time``
  864. Takes two optional arguments:
  865. .. attribute:: input_date_formats
  866. A list of formats used to attempt to convert a string to a valid
  867. ``datetime.date`` object.
  868. If no ``input_date_formats`` argument is provided, the default input formats
  869. for :class:`DateField` are used.
  870. .. attribute:: input_time_formats
  871. A list of formats used to attempt to convert a string to a valid
  872. ``datetime.time`` object.
  873. If no ``input_time_formats`` argument is provided, the default input formats
  874. for :class:`TimeField` are used.
  875. .. _fields-which-handle-relationships:
  876. Fields which handle relationships
  877. =================================
  878. Two fields are available for representing relationships between
  879. models: :class:`ModelChoiceField` and
  880. :class:`ModelMultipleChoiceField`. Both of these fields require a
  881. single ``queryset`` parameter that is used to create the choices for
  882. the field. Upon form validation, these fields will place either one
  883. model object (in the case of ``ModelChoiceField``) or multiple model
  884. objects (in the case of ``ModelMultipleChoiceField``) into the
  885. ``cleaned_data`` dictionary of the form.
  886. For more complex uses, you can specify ``queryset=None`` when declaring the
  887. form field and then populate the ``queryset`` in the form's ``__init__()``
  888. method::
  889. class FooMultipleChoiceForm(forms.Form):
  890. foo_select = forms.ModelMultipleChoiceField(queryset=None)
  891. def __init__(self, *args, **kwargs):
  892. super().__init__(*args, **kwargs)
  893. self.fields['foo_select'].queryset = ...
  894. Both ``ModelChoiceField`` and ``ModelMultipleChoiceField`` have an ``iterator``
  895. attribute which specifies the class used to iterate over the queryset when
  896. generating choices. See :ref:`iterating-relationship-choices` for details.
  897. ``ModelChoiceField``
  898. --------------------
  899. .. class:: ModelChoiceField(**kwargs)
  900. * Default widget: :class:`Select`
  901. * Empty value: ``None``
  902. * Normalizes to: A model instance.
  903. * Validates that the given id exists in the queryset.
  904. * Error message keys: ``required``, ``invalid_choice``
  905. Allows the selection of a single model object, suitable for representing a
  906. foreign key. Note that the default widget for ``ModelChoiceField`` becomes
  907. impractical when the number of entries increases. You should avoid using it
  908. for more than 100 items.
  909. A single argument is required:
  910. .. attribute:: queryset
  911. A ``QuerySet`` of model objects from which the choices for the field
  912. are derived and which is used to validate the user's selection. It's
  913. evaluated when the form is rendered.
  914. ``ModelChoiceField`` also takes two optional arguments:
  915. .. attribute:: empty_label
  916. By default the ``<select>`` widget used by ``ModelChoiceField`` will have an
  917. empty choice at the top of the list. You can change the text of this
  918. label (which is ``"---------"`` by default) with the ``empty_label``
  919. attribute, or you can disable the empty label entirely by setting
  920. ``empty_label`` to ``None``::
  921. # A custom empty label
  922. field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)")
  923. # No empty label
  924. field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
  925. Note that if a ``ModelChoiceField`` is required and has a default
  926. initial value, no empty choice is created (regardless of the value
  927. of ``empty_label``).
  928. .. attribute:: to_field_name
  929. This optional argument is used to specify the field to use as the value
  930. of the choices in the field's widget. Be sure it's a unique field for
  931. the model, otherwise the selected value could match more than one
  932. object. By default it is set to ``None``, in which case the primary key
  933. of each object will be used. For example::
  934. # No custom to_field_name
  935. field1 = forms.ModelChoiceField(queryset=...)
  936. would yield:
  937. .. code-block:: html
  938. <select id="id_field1" name="field1">
  939. <option value="obj1.pk">Object1</option>
  940. <option value="obj2.pk">Object2</option>
  941. ...
  942. </select>
  943. and::
  944. # to_field_name provided
  945. field2 = forms.ModelChoiceField(queryset=..., to_field_name="name")
  946. would yield:
  947. .. code-block:: html
  948. <select id="id_field2" name="field2">
  949. <option value="obj1.name">Object1</option>
  950. <option value="obj2.name">Object2</option>
  951. ...
  952. </select>
  953. ``ModelChoiceField`` also has the attribute:
  954. .. attribute:: iterator
  955. The iterator class used to generate field choices from ``queryset``. By
  956. default, :class:`ModelChoiceIterator`.
  957. The ``__str__()`` method of the model will be called to generate string
  958. representations of the objects for use in the field's choices. To provide
  959. customized representations, subclass ``ModelChoiceField`` and override
  960. ``label_from_instance``. This method will receive a model object and should
  961. return a string suitable for representing it. For example::
  962. from django.forms import ModelChoiceField
  963. class MyModelChoiceField(ModelChoiceField):
  964. def label_from_instance(self, obj):
  965. return "My Object #%i" % obj.id
  966. ``ModelMultipleChoiceField``
  967. ----------------------------
  968. .. class:: ModelMultipleChoiceField(**kwargs)
  969. * Default widget: :class:`SelectMultiple`
  970. * Empty value: An empty ``QuerySet`` (self.queryset.none())
  971. * Normalizes to: A ``QuerySet`` of model instances.
  972. * Validates that every id in the given list of values exists in the
  973. queryset.
  974. * Error message keys: ``required``, ``invalid_list``, ``invalid_choice``,
  975. ``invalid_pk_value``
  976. The ``invalid_choice`` message may contain ``%(value)s`` and the
  977. ``invalid_pk_value`` message may contain ``%(pk)s``, which will be
  978. substituted by the appropriate values.
  979. Allows the selection of one or more model objects, suitable for
  980. representing a many-to-many relation. As with :class:`ModelChoiceField`,
  981. you can use ``label_from_instance`` to customize the object
  982. representations.
  983. A single argument is required:
  984. .. attribute:: queryset
  985. Same as :class:`ModelChoiceField.queryset`.
  986. Takes one optional argument:
  987. .. attribute:: to_field_name
  988. Same as :class:`ModelChoiceField.to_field_name`.
  989. ``ModelMultipleChoiceField`` also has the attribute:
  990. .. attribute:: iterator
  991. Same as :class:`ModelChoiceField.iterator`.
  992. .. deprecated:: 3.1
  993. The ``list`` message is deprecated, use ``invalid_list`` instead.
  994. .. _iterating-relationship-choices:
  995. Iterating relationship choices
  996. ------------------------------
  997. By default, :class:`ModelChoiceField` and :class:`ModelMultipleChoiceField` use
  998. :class:`ModelChoiceIterator` to generate their field ``choices``.
  999. When iterated, ``ModelChoiceIterator`` yields 2-tuple choices containing
  1000. :class:`ModelChoiceIteratorValue` instances as the first ``value`` element in
  1001. each choice. ``ModelChoiceIteratorValue`` wraps the choice value while
  1002. maintaining a reference to the source model instance that can be used in custom
  1003. widget implementations, for example, to add `data-* attributes`_ to
  1004. ``<option>`` elements.
  1005. .. _`data-* attributes`: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*
  1006. For example, consider the following models::
  1007. from django.db import models
  1008. class Topping(models.Model):
  1009. name = models.CharField(max_length=100)
  1010. price = models.DecimalField(decimal_places=2, max_digits=6)
  1011. def __str__(self):
  1012. return self.name
  1013. class Pizza(models.Model):
  1014. topping = models.ForeignKey(Topping, on_delete=models.CASCADE)
  1015. You can use a :class:`~django.forms.Select` widget subclass to include
  1016. the value of ``Topping.price`` as the HTML attribute ``data-price`` for each
  1017. ``<option>`` element::
  1018. from django import forms
  1019. class ToppingSelect(forms.Select):
  1020. def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
  1021. option = super().create_option(name, value, label, selected, index, subindex, attrs)
  1022. if value:
  1023. option['attrs']['data-price'] = value.instance.price
  1024. return option
  1025. class PizzaForm(forms.ModelForm):
  1026. class Meta:
  1027. model = Pizza
  1028. fields = ['topping']
  1029. widgets = {'topping': ToppingSelect}
  1030. This will render the ``Pizza.topping`` select as:
  1031. .. code-block:: html
  1032. <select id="id_topping" name="topping" required>
  1033. <option value="" selected>---------</option>
  1034. <option value="1" data-price="1.50">mushrooms</option>
  1035. <option value="2" data-price="1.25">onions</option>
  1036. <option value="3" data-price="1.75">peppers</option>
  1037. <option value="4" data-price="2.00">pineapple</option>
  1038. </select>
  1039. For more advanced usage you may subclass ``ModelChoiceIterator`` in order to
  1040. customize the yielded 2-tuple choices.
  1041. ``ModelChoiceIterator``
  1042. ~~~~~~~~~~~~~~~~~~~~~~~
  1043. .. class:: ModelChoiceIterator(field)
  1044. The default class assigned to the ``iterator`` attribute of
  1045. :class:`ModelChoiceField` and :class:`ModelMultipleChoiceField`. An
  1046. iterable that yields 2-tuple choices from the queryset.
  1047. A single argument is required:
  1048. .. attribute:: field
  1049. The instance of ``ModelChoiceField`` or ``ModelMultipleChoiceField`` to
  1050. iterate and yield choices.
  1051. ``ModelChoiceIterator`` has the following method:
  1052. .. method:: __iter__()
  1053. Yields 2-tuple choices, in the ``(value, label)`` format used by
  1054. :attr:`ChoiceField.choices`. The first ``value`` element is a
  1055. :class:`ModelChoiceIteratorValue` instance.
  1056. .. versionchanged:: 3.1
  1057. In older versions, the first ``value`` element in the choice tuple
  1058. is the ``field`` value itself, rather than a
  1059. ``ModelChoiceIteratorValue`` instance. In most cases this proxies
  1060. transparently but, if you need the ``field`` value itself, use the
  1061. :attr:`ModelChoiceIteratorValue.value` attribute instead.
  1062. ``ModelChoiceIteratorValue``
  1063. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1064. .. class:: ModelChoiceIteratorValue(value, instance)
  1065. .. versionadded:: 3.1
  1066. Two arguments are required:
  1067. .. attribute:: value
  1068. The value of the choice. This value is used to render the ``value``
  1069. attribute of an HTML ``<option>`` element.
  1070. .. attribute:: instance
  1071. The model instance from the queryset. The instance can be accessed in
  1072. custom ``ChoiceWidget.create_option()`` implementations to adjust the
  1073. rendered HTML.
  1074. ``ModelChoiceIteratorValue`` has the following method:
  1075. .. method:: __str__()
  1076. Return ``value`` as a string to be rendered in HTML.
  1077. Creating custom fields
  1078. ======================
  1079. If the built-in ``Field`` classes don't meet your needs, you can create custom
  1080. ``Field`` classes. To do this, create a subclass of ``django.forms.Field``. Its
  1081. only requirements are that it implement a ``clean()`` method and that its
  1082. ``__init__()`` method accept the core arguments mentioned above (``required``,
  1083. ``label``, ``initial``, ``widget``, ``help_text``).
  1084. You can also customize how a field will be accessed by overriding
  1085. :meth:`~django.forms.Field.get_bound_field()`.