fields.txt 54 KB

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