widgets.txt 34 KB

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