fields.txt 53 KB

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