widgets.txt 29 KB

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