widgets.txt 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. =======
  2. Widgets
  3. =======
  4. .. module:: django.forms.widgets
  5. :synopsis: Django's built-in form widgets.
  6. .. currentmodule:: django.forms
  7. A widget is Django's representation of an HTML input element. The widget
  8. handles the rendering of the HTML, and the extraction of data from a GET/POST
  9. dictionary that corresponds to the widget.
  10. The HTML generated by the built-in widgets uses HTML5 syntax, targeting
  11. ``<!DOCTYPE html>``. For example, it uses boolean attributes such as ``checked``
  12. rather than the XHTML style of ``checked='checked'``.
  13. .. tip::
  14. Widgets should not be confused with the :doc:`form fields </ref/forms/fields>`.
  15. Form fields deal with the logic of input validation and are used directly
  16. in templates. Widgets deal with rendering of HTML form input elements on
  17. the web page and extraction of raw submitted data. However, widgets do
  18. need to be :ref:`assigned <widget-to-field>` to form fields.
  19. .. _widget-to-field:
  20. Specifying widgets
  21. ==================
  22. Whenever you specify a field on a form, Django will use a default widget
  23. that is appropriate to the type of data that is to be displayed. To find
  24. which widget is used on which field, see the documentation about
  25. :ref:`built-in-fields`.
  26. However, if you want to use a different widget for a field, you can
  27. use the :attr:`~Field.widget` argument on the field definition. For example::
  28. from django import forms
  29. class CommentForm(forms.Form):
  30. name = forms.CharField()
  31. url = forms.URLField()
  32. comment = forms.CharField(widget=forms.Textarea)
  33. This would specify a form with a comment that uses a larger :class:`Textarea`
  34. widget, rather than the default :class:`TextInput` widget.
  35. Setting arguments for widgets
  36. =============================
  37. Many widgets have optional extra arguments; they can be set when defining the
  38. widget on the field. In the following example, the
  39. :attr:`~django.forms.SelectDateWidget.years` attribute is set for a
  40. :class:`~django.forms.SelectDateWidget`::
  41. from django import forms
  42. BIRTH_YEAR_CHOICES = ['1980', '1981', '1982']
  43. FAVORITE_COLORS_CHOICES = [
  44. ('blue', 'Blue'),
  45. ('green', 'Green'),
  46. ('black', 'Black'),
  47. ]
  48. class SimpleForm(forms.Form):
  49. birth_year = forms.DateField(widget=forms.SelectDateWidget(years=BIRTH_YEAR_CHOICES))
  50. favorite_colors = forms.MultipleChoiceField(
  51. required=False,
  52. widget=forms.CheckboxSelectMultiple,
  53. choices=FAVORITE_COLORS_CHOICES,
  54. )
  55. See the :ref:`built-in widgets` for more information about which widgets
  56. are available and which arguments they accept.
  57. Widgets inheriting from the ``Select`` widget
  58. =============================================
  59. Widgets inheriting from the :class:`Select` widget deal with choices. They
  60. present the user with a list of options to choose from. The different widgets
  61. present this choice differently; the :class:`Select` widget itself uses a
  62. ``<select>`` HTML list representation, while :class:`RadioSelect` uses radio
  63. buttons.
  64. :class:`Select` widgets are used by default on :class:`ChoiceField` fields. The
  65. choices displayed on the widget are inherited from the :class:`ChoiceField` and
  66. changing :attr:`ChoiceField.choices` will update :attr:`Select.choices`. For
  67. example::
  68. >>> from django import forms
  69. >>> CHOICES = [('1', 'First'), ('2', 'Second')]
  70. >>> choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
  71. >>> choice_field.choices
  72. [('1', 'First'), ('2', 'Second')]
  73. >>> choice_field.widget.choices
  74. [('1', 'First'), ('2', 'Second')]
  75. >>> choice_field.widget.choices = []
  76. >>> choice_field.choices = [('1', 'First and only')]
  77. >>> choice_field.widget.choices
  78. [('1', 'First and only')]
  79. Widgets which offer a :attr:`~Select.choices` attribute can however be used
  80. with fields which are not based on choice -- such as a :class:`CharField` --
  81. but it is recommended to use a :class:`ChoiceField`-based field when the
  82. choices are inherent to the model and not just the representational widget.
  83. Customizing widget instances
  84. ============================
  85. When Django renders a widget as HTML, it only renders very minimal markup -
  86. Django doesn't add class names, or any other widget-specific attributes. This
  87. means, for example, that all :class:`TextInput` widgets will appear the same
  88. on your web pages.
  89. There are two ways to customize widgets: :ref:`per widget instance
  90. <styling-widget-instances>` and :ref:`per widget class <styling-widget-classes>`.
  91. .. _styling-widget-instances:
  92. Styling widget instances
  93. ------------------------
  94. If you want to make one widget instance look different from another, you will
  95. need to specify additional attributes at the time when the widget object is
  96. instantiated and assigned to a form field (and perhaps add some rules to your
  97. CSS files).
  98. For example, take the following form::
  99. from django import forms
  100. class CommentForm(forms.Form):
  101. name = forms.CharField()
  102. url = forms.URLField()
  103. comment = forms.CharField()
  104. This form will include three default :class:`TextInput` widgets, with default
  105. rendering -- no CSS class, no extra attributes. This means that the input boxes
  106. provided for each widget will be rendered exactly the same::
  107. >>> f = CommentForm(auto_id=False)
  108. >>> f.as_table()
  109. <tr><th>Name:</th><td><input type="text" name="name" required></td></tr>
  110. <tr><th>Url:</th><td><input type="url" name="url" required></td></tr>
  111. <tr><th>Comment:</th><td><input type="text" name="comment" required></td></tr>
  112. On a real web page, you probably don't want every widget to look the same. You
  113. might want a larger input element for the comment, and you might want the
  114. 'name' widget to have some special CSS class. It is also possible to specify
  115. the 'type' attribute to take advantage of the new HTML5 input types. To do
  116. this, you use the :attr:`Widget.attrs` argument when creating the widget::
  117. class CommentForm(forms.Form):
  118. name = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))
  119. url = forms.URLField()
  120. comment = forms.CharField(widget=forms.TextInput(attrs={'size': '40'}))
  121. You can also modify a widget in the form definition::
  122. class CommentForm(forms.Form):
  123. name = forms.CharField()
  124. url = forms.URLField()
  125. comment = forms.CharField()
  126. name.widget.attrs.update({'class': 'special'})
  127. comment.widget.attrs.update(size='40')
  128. Or if the field isn't declared directly on the form (such as model form fields),
  129. you can use the :attr:`Form.fields` attribute::
  130. class CommentForm(forms.ModelForm):
  131. def __init__(self, *args, **kwargs):
  132. super().__init__(*args, **kwargs)
  133. self.fields['name'].widget.attrs.update({'class': 'special'})
  134. self.fields['comment'].widget.attrs.update(size='40')
  135. Django will then include the extra attributes in the rendered output:
  136. >>> f = CommentForm(auto_id=False)
  137. >>> f.as_table()
  138. <tr><th>Name:</th><td><input type="text" name="name" class="special" required></td></tr>
  139. <tr><th>Url:</th><td><input type="url" name="url" required></td></tr>
  140. <tr><th>Comment:</th><td><input type="text" name="comment" size="40" required></td></tr>
  141. You can also set the HTML ``id`` using :attr:`~Widget.attrs`. See
  142. :attr:`BoundField.id_for_label` for an example.
  143. .. _styling-widget-classes:
  144. Styling widget classes
  145. ----------------------
  146. With widgets, it is possible to add assets (``css`` and ``javascript``)
  147. and more deeply customize their appearance and behavior.
  148. In a nutshell, you will need to subclass the widget and either
  149. :ref:`define a "Media" inner class <assets-as-a-static-definition>` or
  150. :ref:`create a "media" property <dynamic-property>`.
  151. These methods involve somewhat advanced Python programming and are described in
  152. detail in the :doc:`Form Assets </topics/forms/media>` topic guide.
  153. .. _base-widget-classes:
  154. Base widget classes
  155. ===================
  156. Base widget classes :class:`Widget` and :class:`MultiWidget` are subclassed by
  157. all the :ref:`built-in widgets <built-in widgets>` and may serve as a
  158. foundation for custom widgets.
  159. ``Widget``
  160. ----------
  161. .. class:: Widget(attrs=None)
  162. This abstract class cannot be rendered, but provides the basic attribute
  163. :attr:`~Widget.attrs`. You may also implement or override the
  164. :meth:`~Widget.render()` method on custom widgets.
  165. .. attribute:: Widget.attrs
  166. A dictionary containing HTML attributes to be set on the rendered
  167. widget.
  168. .. code-block:: pycon
  169. >>> from django import forms
  170. >>> name = forms.TextInput(attrs={'size': 10, 'title': 'Your name'})
  171. >>> name.render('name', 'A name')
  172. '<input title="Your name" type="text" name="name" value="A name" size="10">'
  173. If you assign a value of ``True`` or ``False`` to an attribute,
  174. it will be rendered as an HTML5 boolean attribute::
  175. >>> name = forms.TextInput(attrs={'required': True})
  176. >>> name.render('name', 'A name')
  177. '<input name="name" type="text" value="A name" required>'
  178. >>>
  179. >>> name = forms.TextInput(attrs={'required': False})
  180. >>> name.render('name', 'A name')
  181. '<input name="name" type="text" value="A name">'
  182. .. attribute:: Widget.supports_microseconds
  183. An attribute that defaults to ``True``. If set to ``False``, the
  184. microseconds part of :class:`~datetime.datetime` and
  185. :class:`~datetime.time` values will be set to ``0``.
  186. .. method:: format_value(value)
  187. Cleans and returns a value for use in the widget template. ``value``
  188. isn't guaranteed to be valid input, therefore subclass implementations
  189. should program defensively.
  190. .. method:: get_context(name, value, attrs)
  191. Returns a dictionary of values to use when rendering the widget
  192. template. By default, the dictionary contains a single key,
  193. ``'widget'``, which is a dictionary representation of the widget
  194. containing the following keys:
  195. * ``'name'``: The name of the field from the ``name`` argument.
  196. * ``'is_hidden'``: A boolean indicating whether or not this widget is
  197. hidden.
  198. * ``'required'``: A boolean indicating whether or not the field for
  199. this widget is required.
  200. * ``'value'``: The value as returned by :meth:`format_value`.
  201. * ``'attrs'``: HTML attributes to be set on the rendered widget. The
  202. combination of the :attr:`attrs` attribute and the ``attrs`` argument.
  203. * ``'template_name'``: The value of ``self.template_name``.
  204. ``Widget`` subclasses can provide custom context values by overriding
  205. this method.
  206. .. method:: id_for_label(id_)
  207. Returns the HTML ID attribute of this widget for use by a ``<label>``,
  208. given the ID of the field. Returns ``None`` if an ID isn't available.
  209. This hook is necessary because some widgets have multiple HTML
  210. elements and, thus, multiple IDs. In that case, this method should
  211. return an ID value that corresponds to the first ID in the widget's
  212. tags.
  213. .. method:: render(name, value, attrs=None, renderer=None)
  214. Renders a widget to HTML using the given renderer. If ``renderer`` is
  215. ``None``, the renderer from the :setting:`FORM_RENDERER` setting is
  216. used.
  217. .. method:: value_from_datadict(data, files, name)
  218. Given a dictionary of data and this widget's name, returns the value
  219. of this widget. ``files`` may contain data coming from
  220. :attr:`request.FILES <django.http.HttpRequest.FILES>`. Returns ``None``
  221. if a value wasn't provided. Note also that ``value_from_datadict`` may
  222. be called more than once during handling of form data, so if you
  223. customize it and add expensive processing, you should implement some
  224. caching mechanism yourself.
  225. .. method:: value_omitted_from_data(data, files, name)
  226. Given ``data`` and ``files`` dictionaries and this widget's name,
  227. returns whether or not there's data or files for the widget.
  228. The method's result affects whether or not a field in a model form
  229. :ref:`falls back to its default <topics-modelform-save>`.
  230. Special cases are :class:`~django.forms.CheckboxInput`,
  231. :class:`~django.forms.CheckboxSelectMultiple`, and
  232. :class:`~django.forms.SelectMultiple`, which always return
  233. ``False`` because an unchecked checkbox and unselected
  234. ``<select multiple>`` don't appear in the data of an HTML form
  235. submission, so it's unknown whether or not the user submitted a value.
  236. .. attribute:: Widget.use_fieldset
  237. .. versionadded:: 4.1
  238. An attribute to identify if the widget should be grouped in a
  239. ``<fieldset>`` with a ``<legend>`` when rendered. Defaults to ``False``
  240. but is ``True`` when the widget contains multiple ``<input>`` tags such as
  241. :class:`~django.forms.CheckboxSelectMultiple`,
  242. :class:`~django.forms.RadioSelect`,
  243. :class:`~django.forms.MultiWidget`,
  244. :class:`~django.forms.SplitDateTimeWidget`, and
  245. :class:`~django.forms.SelectDateWidget`.
  246. .. method:: use_required_attribute(initial)
  247. Given a form field's ``initial`` value, returns whether or not the
  248. widget can be rendered with the ``required`` HTML attribute. Forms use
  249. this method along with :attr:`Field.required
  250. <django.forms.Field.required>` and :attr:`Form.use_required_attribute
  251. <django.forms.Form.use_required_attribute>` to determine whether or not
  252. to display the ``required`` attribute for each field.
  253. By default, returns ``False`` for hidden widgets and ``True``
  254. otherwise. Special cases are :class:`~django.forms.FileInput` and
  255. :class:`~django.forms.ClearableFileInput`, which return ``False`` when
  256. ``initial`` is set, and :class:`~django.forms.CheckboxSelectMultiple`,
  257. which always returns ``False`` because browser validation would require
  258. all checkboxes to be checked instead of at least one.
  259. Override this method in custom widgets that aren't compatible with
  260. browser validation. For example, a WSYSIWG text editor widget backed by
  261. a hidden ``textarea`` element may want to always return ``False`` to
  262. avoid browser validation on the hidden field.
  263. ``MultiWidget``
  264. ---------------
  265. .. class:: MultiWidget(widgets, attrs=None)
  266. A widget that is composed of multiple widgets.
  267. :class:`~django.forms.MultiWidget` works hand in hand with the
  268. :class:`~django.forms.MultiValueField`.
  269. :class:`MultiWidget` has one required argument:
  270. .. attribute:: MultiWidget.widgets
  271. An iterable containing the widgets needed. For example::
  272. >>> from django.forms import MultiWidget, TextInput
  273. >>> widget = MultiWidget(widgets=[TextInput, TextInput])
  274. >>> widget.render('name', ['john', 'paul'])
  275. '<input type="text" name="name_0" value="john"><input type="text" name="name_1" value="paul">'
  276. You may provide a dictionary in order to specify custom suffixes for
  277. the ``name`` attribute on each subwidget. In this case, for each
  278. ``(key, widget)`` pair, the key will be appended to the ``name`` of the
  279. widget in order to generate the attribute value. You may provide the
  280. empty string (``''``) for a single key, in order to suppress the suffix
  281. for one widget. For example::
  282. >>> widget = MultiWidget(widgets={'': TextInput, 'last': TextInput})
  283. >>> widget.render('name', ['john', 'paul'])
  284. '<input type="text" name="name" value="john"><input type="text" name="name_last" value="paul">'
  285. And one required method:
  286. .. method:: decompress(value)
  287. This method takes a single "compressed" value from the field and
  288. returns a list of "decompressed" values. The input value can be
  289. assumed valid, but not necessarily non-empty.
  290. This method **must be implemented** by the subclass, and since the
  291. value may be empty, the implementation must be defensive.
  292. The rationale behind "decompression" is that it is necessary to "split"
  293. the combined value of the form field into the values for each widget.
  294. An example of this is how :class:`SplitDateTimeWidget` turns a
  295. :class:`~datetime.datetime` value into a list with date and time split
  296. into two separate values::
  297. from django.forms import MultiWidget
  298. class SplitDateTimeWidget(MultiWidget):
  299. # ...
  300. def decompress(self, value):
  301. if value:
  302. return [value.date(), value.time()]
  303. return [None, None]
  304. .. tip::
  305. Note that :class:`~django.forms.MultiValueField` has a
  306. complementary method :meth:`~django.forms.MultiValueField.compress`
  307. with the opposite responsibility - to combine cleaned values of
  308. all member fields into one.
  309. It provides some custom context:
  310. .. method:: get_context(name, value, attrs)
  311. In addition to the ``'widget'`` key described in
  312. :meth:`Widget.get_context`, ``MultiWidget`` adds a
  313. ``widget['subwidgets']`` key.
  314. These can be looped over in the widget template:
  315. .. code-block:: html+django
  316. {% for subwidget in widget.subwidgets %}
  317. {% include subwidget.template_name with widget=subwidget %}
  318. {% endfor %}
  319. Here's an example widget which subclasses :class:`MultiWidget` to display
  320. a date with the day, month, and year in different select boxes. This widget
  321. is intended to be used with a :class:`~django.forms.DateField` rather than
  322. a :class:`~django.forms.MultiValueField`, thus we have implemented
  323. :meth:`~Widget.value_from_datadict`::
  324. from datetime import date
  325. from django import forms
  326. class DateSelectorWidget(forms.MultiWidget):
  327. def __init__(self, attrs=None):
  328. days = [(day, day) for day in range(1, 32)]
  329. months = [(month, month) for month in range(1, 13)]
  330. years = [(year, year) for year in [2018, 2019, 2020]]
  331. widgets = [
  332. forms.Select(attrs=attrs, choices=days),
  333. forms.Select(attrs=attrs, choices=months),
  334. forms.Select(attrs=attrs, choices=years),
  335. ]
  336. super().__init__(widgets, attrs)
  337. def decompress(self, value):
  338. if isinstance(value, date):
  339. return [value.day, value.month, value.year]
  340. elif isinstance(value, str):
  341. year, month, day = value.split('-')
  342. return [day, month, year]
  343. return [None, None, None]
  344. def value_from_datadict(self, data, files, name):
  345. day, month, year = super().value_from_datadict(data, files, name)
  346. # DateField expects a single string that it can parse into a date.
  347. return '{}-{}-{}'.format(year, month, day)
  348. The constructor creates several :class:`Select` widgets in a list. The
  349. ``super()`` method uses this list to set up the widget.
  350. The required method :meth:`~MultiWidget.decompress` breaks up a
  351. ``datetime.date`` value into the day, month, and year values corresponding
  352. to each widget. If an invalid date was selected, such as the non-existent
  353. 30th February, the :class:`~django.forms.DateField` passes this method a
  354. string instead, so that needs parsing. The final ``return`` handles when
  355. ``value`` is ``None``, meaning we don't have any defaults for our
  356. subwidgets.
  357. The default implementation of :meth:`~Widget.value_from_datadict` returns a
  358. list of values corresponding to each ``Widget``. This is appropriate when
  359. using a ``MultiWidget`` with a :class:`~django.forms.MultiValueField`. But
  360. since we want to use this widget with a :class:`~django.forms.DateField`,
  361. which takes a single value, we have overridden this method. The
  362. implementation here combines the data from the subwidgets into a string in
  363. the format that :class:`~django.forms.DateField` expects.
  364. .. _built-in widgets:
  365. Built-in widgets
  366. ================
  367. Django provides a representation of all the basic HTML widgets, plus some
  368. commonly used groups of widgets in the ``django.forms.widgets`` module,
  369. including :ref:`the input of text <text-widgets>`, :ref:`various checkboxes
  370. and selectors <selector-widgets>`, :ref:`uploading files <file-upload-widgets>`,
  371. and :ref:`handling of multi-valued input <composite-widgets>`.
  372. .. _text-widgets:
  373. Widgets handling input of text
  374. ------------------------------
  375. These widgets make use of the HTML elements ``input`` and ``textarea``.
  376. ``TextInput``
  377. ~~~~~~~~~~~~~
  378. .. class:: TextInput
  379. * ``input_type``: ``'text'``
  380. * ``template_name``: ``'django/forms/widgets/text.html'``
  381. * Renders as: ``<input type="text" ...>``
  382. ``NumberInput``
  383. ~~~~~~~~~~~~~~~
  384. .. class:: NumberInput
  385. * ``input_type``: ``'number'``
  386. * ``template_name``: ``'django/forms/widgets/number.html'``
  387. * Renders as: ``<input type="number" ...>``
  388. Beware that not all browsers support entering localized numbers in
  389. ``number`` input types. Django itself avoids using them for fields having
  390. their :attr:`~django.forms.Field.localize` property set to ``True``.
  391. ``EmailInput``
  392. ~~~~~~~~~~~~~~
  393. .. class:: EmailInput
  394. * ``input_type``: ``'email'``
  395. * ``template_name``: ``'django/forms/widgets/email.html'``
  396. * Renders as: ``<input type="email" ...>``
  397. ``URLInput``
  398. ~~~~~~~~~~~~
  399. .. class:: URLInput
  400. * ``input_type``: ``'url'``
  401. * ``template_name``: ``'django/forms/widgets/url.html'``
  402. * Renders as: ``<input type="url" ...>``
  403. ``PasswordInput``
  404. ~~~~~~~~~~~~~~~~~
  405. .. class:: PasswordInput
  406. * ``input_type``: ``'password'``
  407. * ``template_name``: ``'django/forms/widgets/password.html'``
  408. * Renders as: ``<input type="password" ...>``
  409. Takes one optional argument:
  410. .. attribute:: PasswordInput.render_value
  411. Determines whether the widget will have a value filled in when the
  412. form is re-displayed after a validation error (default is ``False``).
  413. ``HiddenInput``
  414. ~~~~~~~~~~~~~~~
  415. .. class:: HiddenInput
  416. * ``input_type``: ``'hidden'``
  417. * ``template_name``: ``'django/forms/widgets/hidden.html'``
  418. * Renders as: ``<input type="hidden" ...>``
  419. Note that there also is a :class:`MultipleHiddenInput` widget that
  420. encapsulates a set of hidden input elements.
  421. ``DateInput``
  422. ~~~~~~~~~~~~~
  423. .. class:: DateInput
  424. * ``input_type``: ``'text'``
  425. * ``template_name``: ``'django/forms/widgets/date.html'``
  426. * Renders as: ``<input type="text" ...>``
  427. Takes same arguments as :class:`TextInput`, with one more optional argument:
  428. .. attribute:: DateInput.format
  429. The format in which this field's initial value will be displayed.
  430. If no ``format`` argument is provided, the default format is the first
  431. format found in :setting:`DATE_INPUT_FORMATS` and respects
  432. :doc:`/topics/i18n/formatting`.
  433. ``DateTimeInput``
  434. ~~~~~~~~~~~~~~~~~
  435. .. class:: DateTimeInput
  436. * ``input_type``: ``'text'``
  437. * ``template_name``: ``'django/forms/widgets/datetime.html'``
  438. * Renders as: ``<input type="text" ...>``
  439. Takes same arguments as :class:`TextInput`, with one more optional argument:
  440. .. attribute:: DateTimeInput.format
  441. The format in which this field's initial value will be displayed.
  442. If no ``format`` argument is provided, the default format is the first
  443. format found in :setting:`DATETIME_INPUT_FORMATS` and respects
  444. :doc:`/topics/i18n/formatting`.
  445. By default, the microseconds part of the time value is always set to ``0``.
  446. If microseconds are required, use a subclass with the
  447. :attr:`~Widget.supports_microseconds` attribute set to ``True``.
  448. ``TimeInput``
  449. ~~~~~~~~~~~~~
  450. .. class:: TimeInput
  451. * ``input_type``: ``'text'``
  452. * ``template_name``: ``'django/forms/widgets/time.html'``
  453. * Renders as: ``<input type="text" ...>``
  454. Takes same arguments as :class:`TextInput`, with one more optional argument:
  455. .. attribute:: TimeInput.format
  456. The format in which this field's initial value will be displayed.
  457. If no ``format`` argument is provided, the default format is the first
  458. format found in :setting:`TIME_INPUT_FORMATS` and respects
  459. :doc:`/topics/i18n/formatting`.
  460. For the treatment of microseconds, see :class:`DateTimeInput`.
  461. ``Textarea``
  462. ~~~~~~~~~~~~
  463. .. class:: Textarea
  464. * ``template_name``: ``'django/forms/widgets/textarea.html'``
  465. * Renders as: ``<textarea>...</textarea>``
  466. .. _selector-widgets:
  467. Selector and checkbox widgets
  468. -----------------------------
  469. These widgets make use of the HTML elements ``<select>``,
  470. ``<input type="checkbox">``, and ``<input type="radio">``.
  471. Widgets that render multiple choices have an ``option_template_name`` attribute
  472. that specifies the template used to render each choice. For example, for the
  473. :class:`Select` widget, ``select_option.html`` renders the ``<option>`` for a
  474. ``<select>``.
  475. ``CheckboxInput``
  476. ~~~~~~~~~~~~~~~~~
  477. .. class:: CheckboxInput
  478. * ``input_type``: ``'checkbox'``
  479. * ``template_name``: ``'django/forms/widgets/checkbox.html'``
  480. * Renders as: ``<input type="checkbox" ...>``
  481. Takes one optional argument:
  482. .. attribute:: CheckboxInput.check_test
  483. A callable that takes the value of the ``CheckboxInput`` and returns
  484. ``True`` if the checkbox should be checked for that value.
  485. ``Select``
  486. ~~~~~~~~~~
  487. .. class:: Select
  488. * ``template_name``: ``'django/forms/widgets/select.html'``
  489. * ``option_template_name``: ``'django/forms/widgets/select_option.html'``
  490. * Renders as: ``<select><option ...>...</select>``
  491. .. attribute:: Select.choices
  492. This attribute is optional when the form field does not have a
  493. ``choices`` attribute. If it does, it will override anything you set
  494. here when the attribute is updated on the :class:`Field`.
  495. ``NullBooleanSelect``
  496. ~~~~~~~~~~~~~~~~~~~~~
  497. .. class:: NullBooleanSelect
  498. * ``template_name``: ``'django/forms/widgets/select.html'``
  499. * ``option_template_name``: ``'django/forms/widgets/select_option.html'``
  500. Select widget with options 'Unknown', 'Yes' and 'No'
  501. ``SelectMultiple``
  502. ~~~~~~~~~~~~~~~~~~
  503. .. class:: SelectMultiple
  504. * ``template_name``: ``'django/forms/widgets/select.html'``
  505. * ``option_template_name``: ``'django/forms/widgets/select_option.html'``
  506. Similar to :class:`Select`, but allows multiple selection:
  507. ``<select multiple>...</select>``
  508. ``RadioSelect``
  509. ~~~~~~~~~~~~~~~
  510. .. class:: RadioSelect
  511. * ``template_name``: ``'django/forms/widgets/radio.html'``
  512. * ``option_template_name``: ``'django/forms/widgets/radio_option.html'``
  513. Similar to :class:`Select`, but rendered as a list of radio buttons within
  514. ``<div>`` tags:
  515. .. code-block:: html
  516. <div>
  517. <div><input type="radio" name="..."></div>
  518. ...
  519. </div>
  520. .. versionchanged:: 4.0
  521. So they are announced more concisely by screen readers, radio buttons
  522. were changed to render in ``<div>`` tags.
  523. For more granular control over the generated markup, you can loop over the
  524. radio buttons in the template. Assuming a form ``myform`` with a field
  525. ``beatles`` that uses a ``RadioSelect`` as its widget:
  526. .. code-block:: html+django
  527. <fieldset>
  528. <legend>{{ myform.beatles.label }}</legend>
  529. {% for radio in myform.beatles %}
  530. <div class="myradio">
  531. {{ radio }}
  532. </div>
  533. {% endfor %}
  534. </fieldset>
  535. This would generate the following HTML:
  536. .. code-block:: html
  537. <fieldset>
  538. <legend>Radio buttons</legend>
  539. <div class="myradio">
  540. <label for="id_beatles_0"><input id="id_beatles_0" name="beatles" type="radio" value="john" required> John</label>
  541. </div>
  542. <div class="myradio">
  543. <label for="id_beatles_1"><input id="id_beatles_1" name="beatles" type="radio" value="paul" required> Paul</label>
  544. </div>
  545. <div class="myradio">
  546. <label for="id_beatles_2"><input id="id_beatles_2" name="beatles" type="radio" value="george" required> George</label>
  547. </div>
  548. <div class="myradio">
  549. <label for="id_beatles_3"><input id="id_beatles_3" name="beatles" type="radio" value="ringo" required> Ringo</label>
  550. </div>
  551. </fieldset>
  552. That included the ``<label>`` tags. To get more granular, you can use each
  553. radio button's ``tag``, ``choice_label`` and ``id_for_label`` attributes.
  554. For example, this template...
  555. .. code-block:: html+django
  556. <fieldset>
  557. <legend>{{ myform.beatles.label }}</legend>
  558. {% for radio in myform.beatles %}
  559. <label for="{{ radio.id_for_label }}">
  560. {{ radio.choice_label }}
  561. <span class="radio">{{ radio.tag }}</span>
  562. </label>
  563. {% endfor %}
  564. </fieldset>
  565. ...will result in the following HTML:
  566. .. code-block:: html
  567. <fieldset>
  568. <legend>Radio buttons</legend>
  569. <label for="id_beatles_0">
  570. John
  571. <span class="radio"><input id="id_beatles_0" name="beatles" type="radio" value="john" required></span>
  572. </label>
  573. <label for="id_beatles_1">
  574. Paul
  575. <span class="radio"><input id="id_beatles_1" name="beatles" type="radio" value="paul" required></span>
  576. </label>
  577. <label for="id_beatles_2">
  578. George
  579. <span class="radio"><input id="id_beatles_2" name="beatles" type="radio" value="george" required></span>
  580. </label>
  581. <label for="id_beatles_3">
  582. Ringo
  583. <span class="radio"><input id="id_beatles_3" name="beatles" type="radio" value="ringo" required></span>
  584. </label>
  585. </fieldset>
  586. If you decide not to loop over the radio buttons -- e.g., if your template
  587. includes ``{{ myform.beatles }}`` -- they'll be output in a ``<div>`` with
  588. ``<div>`` tags, as above.
  589. The outer ``<div>`` container receives the ``id`` attribute of the widget,
  590. if defined, or :attr:`BoundField.auto_id` otherwise.
  591. When looping over the radio buttons, the ``label`` and ``input`` tags include
  592. ``for`` and ``id`` attributes, respectively. Each radio button has an
  593. ``id_for_label`` attribute to output the element's ID.
  594. ``CheckboxSelectMultiple``
  595. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  596. .. class:: CheckboxSelectMultiple
  597. * ``template_name``: ``'django/forms/widgets/checkbox_select.html'``
  598. * ``option_template_name``: ``'django/forms/widgets/checkbox_option.html'``
  599. Similar to :class:`SelectMultiple`, but rendered as a list of checkboxes:
  600. .. code-block:: html
  601. <div>
  602. <div><input type="checkbox" name="..." ></div>
  603. ...
  604. </div>
  605. The outer ``<div>`` container receives the ``id`` attribute of the widget,
  606. if defined, or :attr:`BoundField.auto_id` otherwise.
  607. .. versionchanged:: 4.0
  608. So they are announced more concisely by screen readers, checkboxes were
  609. changed to render in ``<div>`` tags.
  610. Like :class:`RadioSelect`, you can loop over the individual checkboxes for the
  611. widget's choices. Unlike :class:`RadioSelect`, the checkboxes won't include the
  612. ``required`` HTML attribute if the field is required because browser validation
  613. would require all checkboxes to be checked instead of at least one.
  614. When looping over the checkboxes, the ``label`` and ``input`` tags include
  615. ``for`` and ``id`` attributes, respectively. Each checkbox has an
  616. ``id_for_label`` attribute to output the element's ID.
  617. .. _file-upload-widgets:
  618. File upload widgets
  619. -------------------
  620. ``FileInput``
  621. ~~~~~~~~~~~~~
  622. .. class:: FileInput
  623. * ``template_name``: ``'django/forms/widgets/file.html'``
  624. * Renders as: ``<input type="file" ...>``
  625. ``ClearableFileInput``
  626. ~~~~~~~~~~~~~~~~~~~~~~
  627. .. class:: ClearableFileInput
  628. * ``template_name``: ``'django/forms/widgets/clearable_file_input.html'``
  629. * Renders as: ``<input type="file" ...>`` with an additional checkbox
  630. input to clear the field's value, if the field is not required and has
  631. initial data.
  632. .. _composite-widgets:
  633. Composite widgets
  634. -----------------
  635. ``MultipleHiddenInput``
  636. ~~~~~~~~~~~~~~~~~~~~~~~
  637. .. class:: MultipleHiddenInput
  638. * ``template_name``: ``'django/forms/widgets/multiple_hidden.html'``
  639. * Renders as: multiple ``<input type="hidden" ...>`` tags
  640. A widget that handles multiple hidden widgets for fields that have a list
  641. of values.
  642. ``SplitDateTimeWidget``
  643. ~~~~~~~~~~~~~~~~~~~~~~~
  644. .. class:: SplitDateTimeWidget
  645. * ``template_name``: ``'django/forms/widgets/splitdatetime.html'``
  646. Wrapper (using :class:`MultiWidget`) around two widgets: :class:`DateInput`
  647. for the date, and :class:`TimeInput` for the time. Must be used with
  648. :class:`SplitDateTimeField` rather than :class:`DateTimeField`.
  649. ``SplitDateTimeWidget`` has several optional arguments:
  650. .. attribute:: SplitDateTimeWidget.date_format
  651. Similar to :attr:`DateInput.format`
  652. .. attribute:: SplitDateTimeWidget.time_format
  653. Similar to :attr:`TimeInput.format`
  654. .. attribute:: SplitDateTimeWidget.date_attrs
  655. .. attribute:: SplitDateTimeWidget.time_attrs
  656. Similar to :attr:`Widget.attrs`. A dictionary containing HTML
  657. attributes to be set on the rendered :class:`DateInput` and
  658. :class:`TimeInput` widgets, respectively. If these attributes aren't
  659. set, :attr:`Widget.attrs` is used instead.
  660. ``SplitHiddenDateTimeWidget``
  661. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  662. .. class:: SplitHiddenDateTimeWidget
  663. * ``template_name``: ``'django/forms/widgets/splithiddendatetime.html'``
  664. Similar to :class:`SplitDateTimeWidget`, but uses :class:`HiddenInput` for
  665. both date and time.
  666. ``SelectDateWidget``
  667. ~~~~~~~~~~~~~~~~~~~~
  668. .. class:: SelectDateWidget
  669. * ``template_name``: ``'django/forms/widgets/select_date.html'``
  670. Wrapper around three :class:`~django.forms.Select` widgets: one each for
  671. month, day, and year.
  672. Takes several optional arguments:
  673. .. attribute:: SelectDateWidget.years
  674. An optional list/tuple of years to use in the "year" select box.
  675. The default is a list containing the current year and the next 9 years.
  676. .. attribute:: SelectDateWidget.months
  677. An optional dict of months to use in the "months" select box.
  678. The keys of the dict correspond to the month number (1-indexed) and
  679. the values are the displayed months::
  680. MONTHS = {
  681. 1:_('jan'), 2:_('feb'), 3:_('mar'), 4:_('apr'),
  682. 5:_('may'), 6:_('jun'), 7:_('jul'), 8:_('aug'),
  683. 9:_('sep'), 10:_('oct'), 11:_('nov'), 12:_('dec')
  684. }
  685. .. attribute:: SelectDateWidget.empty_label
  686. If the :class:`~django.forms.DateField` is not required,
  687. :class:`SelectDateWidget` will have an empty choice at the top of the
  688. list (which is ``---`` by default). You can change the text of this
  689. label with the ``empty_label`` attribute. ``empty_label`` can be a
  690. ``string``, ``list``, or ``tuple``. When a string is used, all select
  691. boxes will each have an empty choice with this label. If ``empty_label``
  692. is a ``list`` or ``tuple`` of 3 string elements, the select boxes will
  693. have their own custom label. The labels should be in this order
  694. ``('year_label', 'month_label', 'day_label')``.
  695. .. code-block:: python
  696. # A custom empty label with string
  697. field1 = forms.DateField(widget=SelectDateWidget(empty_label="Nothing"))
  698. # A custom empty label with tuple
  699. field1 = forms.DateField(
  700. widget=SelectDateWidget(
  701. empty_label=("Choose Year", "Choose Month", "Choose Day"),
  702. ),
  703. )