widgets.txt 32 KB

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