2
0

widgets.txt 37 KB

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