widgets.txt 27 KB

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