widgets.txt 28 KB

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