widgets.txt 32 KB

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