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