widgets.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. =======
  2. Widgets
  3. =======
  4. .. module:: django.forms.widgets
  5. :synopsis: Django's built-in form widgets.
  6. .. currentmodule:: django.forms
  7. A widget is Django's representation of a HTML input element. The widget
  8. handles the rendering of the HTML, and the extraction of data from a GET/POST
  9. dictionary that corresponds to the widget.
  10. .. tip::
  11. Widgets should not be confused with the :doc:`form fields </ref/forms/fields>`.
  12. Form fields deal with the logic of input validation and are used directly
  13. in templates. Widgets deal with rendering of HTML form input elements on
  14. the web page and extraction of raw submitted data. However, widgets do
  15. need to be :ref:`assigned <widget-to-field>` to form fields.
  16. .. _widget-to-field:
  17. Specifying widgets
  18. ------------------
  19. Whenever you specify a field on a form, Django will use a default widget
  20. that is appropriate to the type of data that is to be displayed. To find
  21. which widget is used on which field, see the documentation about
  22. :ref:`built-in fields`.
  23. However, if you want to use a different widget for a field, you can
  24. just use the :attr:`~Field.widget` argument on the field definition. For
  25. example::
  26. from django import forms
  27. class CommentForm(forms.Form):
  28. name = forms.CharField()
  29. url = forms.URLField()
  30. comment = forms.CharField(widget=forms.Textarea)
  31. This would specify a form with a comment that uses a larger :class:`Textarea`
  32. widget, rather than the default :class:`TextInput` widget.
  33. Setting arguments for widgets
  34. -----------------------------
  35. Many widgets have optional extra arguments; they can be set when defining the
  36. widget on the field. In the following example, the
  37. :attr:`~SelectDateWidget.years` attribute is set for a
  38. :class:`~django.forms.extras.widgets.SelectDateWidget`::
  39. from django.forms.fields import DateField, ChoiceField, MultipleChoiceField
  40. from django.forms.widgets import RadioSelect, CheckboxSelectMultiple
  41. from django.forms.extras.widgets import SelectDateWidget
  42. BIRTH_YEAR_CHOICES = ('1980', '1981', '1982')
  43. FAVORITE_COLORS_CHOICES = (('blue', 'Blue'),
  44. ('green', 'Green'),
  45. ('black', 'Black'))
  46. class SimpleForm(forms.Form):
  47. birth_year = DateField(widget=SelectDateWidget(years=BIRTH_YEAR_CHOICES))
  48. favorite_colors = forms.MultipleChoiceField(required=False,
  49. widget=CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES)
  50. See the :ref:`built-in widgets` for more information about which widgets
  51. are available and which arguments they accept.
  52. Widgets inheriting from the Select widget
  53. -----------------------------------------
  54. Widgets inheriting from the :class:`Select` widget deal with choices. They
  55. present the user with a list of options to choose from. The different widgets
  56. present this choice differently; the :class:`Select` widget itself uses a
  57. ``<select>`` HTML list representation, while :class:`RadioSelect` uses radio
  58. buttons.
  59. :class:`Select` widgets are used by default on :class:`ChoiceField` fields. The
  60. choices displayed on the widget are inherited from the :class:`ChoiceField` and
  61. changing :attr:`ChoiceField.choices` will update :attr:`Select.choices`. For
  62. example::
  63. >>> from django import forms
  64. >>> CHOICES = (('1', 'First',), ('2', 'Second',))
  65. >>> choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
  66. >>> choice_field.choices
  67. [('1', 'First'), ('2', 'Second')]
  68. >>> choice_field.widget.choices
  69. [('1', 'First'), ('2', 'Second')]
  70. >>> choice_field.widget.choices = ()
  71. >>> choice_field.choices = (('1', 'First and only',),)
  72. >>> choice_field.widget.choices
  73. [('1', 'First and only')]
  74. Widgets which offer a :attr:`~Select.choices` attribute can however be used
  75. with fields which are not based on choice -- such as a :class:`CharField` --
  76. but it is recommended to use a :class:`ChoiceField`-based field when the
  77. choices are inherent to the model and not just the representational widget.
  78. Customizing widget instances
  79. ----------------------------
  80. When Django renders a widget as HTML, it only renders very minimal markup -
  81. Django doesn't add class names, or any other widget-specific attributes. This
  82. means, for example, that all :class:`TextInput` widgets will appear the same
  83. on your Web pages.
  84. There are two ways to customize widgets: :ref:`per widget instance
  85. <styling-widget-instances>` and :ref:`per widget class <styling-widget-classes>`.
  86. .. _styling-widget-instances:
  87. Styling widget instances
  88. ^^^^^^^^^^^^^^^^^^^^^^^^
  89. If you want to make one widget instance look different from another, you will
  90. need to specify additional attributes at the time when the widget object is
  91. instantiated and assigned to a form field (and perhaps add some rules to your
  92. CSS files).
  93. For example, take the following simple form::
  94. from django import forms
  95. class CommentForm(forms.Form):
  96. name = forms.CharField()
  97. url = forms.URLField()
  98. comment = forms.CharField()
  99. This form will include three default :class:`TextInput` widgets, with default
  100. rendering -- no CSS class, no extra attributes. This means that the input boxes
  101. provided for each widget will be rendered exactly the same::
  102. >>> f = CommentForm(auto_id=False)
  103. >>> f.as_table()
  104. <tr><th>Name:</th><td><input type="text" name="name" /></td></tr>
  105. <tr><th>Url:</th><td><input type="text" name="url"/></td></tr>
  106. <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
  107. On a real Web page, you probably don't want every widget to look the same. You
  108. might want a larger input element for the comment, and you might want the
  109. 'name' widget to have some special CSS class. It is also possible to specify
  110. the 'type' attribute to take advantage of the new HTML5 input types. To do
  111. this, you use the :attr:`Widget.attrs` argument when creating the widget::
  112. class CommentForm(forms.Form):
  113. name = forms.CharField(
  114. widget=forms.TextInput(attrs={'class':'special'}))
  115. url = forms.URLField()
  116. comment = forms.CharField(
  117. widget=forms.TextInput(attrs={'size':'40'}))
  118. Django will then include the extra attributes in the rendered output:
  119. >>> f = CommentForm(auto_id=False)
  120. >>> f.as_table()
  121. <tr><th>Name:</th><td><input type="text" name="name" class="special"/></td></tr>
  122. <tr><th>Url:</th><td><input type="text" name="url"/></td></tr>
  123. <tr><th>Comment:</th><td><input type="text" name="comment" size="40"/></td></tr>
  124. .. _styling-widget-classes:
  125. Styling widget classes
  126. ^^^^^^^^^^^^^^^^^^^^^^
  127. With widgets, it is possible to add media (``css`` and ``javascript``)
  128. and more deeply customize their appearance and behavior.
  129. In a nutshell, you will need to subclass the widget and either
  130. :ref:`define a class "Media" <media-as-a-static-definition>` as a member of the
  131. subclass, or :ref:`create a property "media" <dynamic-property>`, returning an
  132. instance of that class.
  133. These methods involve somewhat advanced Python programming and are described in
  134. detail in the :doc:`Form Media </topics/forms/media>` topic guide.
  135. .. _base-widget-classes:
  136. Base Widget classes
  137. -------------------
  138. Base widget classes :class:`Widget` and :class:`MultiWidget` are subclassed by
  139. all the :ref:`built-in widgets <built-in widgets>` and may serve as a
  140. foundation for custom widgets.
  141. .. class:: Widget(attrs=None)
  142. This abstract class cannot be rendered, but provides the basic attribute
  143. :attr:`~Widget.attrs`. You may also implement or override the
  144. :meth:`~Widget.render()` method on custom widgets.
  145. .. attribute:: Widget.attrs
  146. A dictionary containing HTML attributes to be set on the rendered
  147. widget.
  148. .. code-block:: python
  149. >>> name = forms.TextInput(attrs={'size': 10, 'title': 'Your name',})
  150. >>> name.render('name', 'A name')
  151. u'<input title="Your name" type="text" name="name" value="A name" size="10" />'
  152. .. method:: render(name, value, attrs=None)
  153. Returns HTML for the widget, as a Unicode string. This method must be
  154. implemented by the subclass, otherwise ``NotImplementedError`` will be
  155. raised.
  156. The 'value' given is not guaranteed to be valid input, therefore
  157. subclass implementations should program defensively.
  158. .. class:: MultiWidget(widgets, attrs=None)
  159. A widget that is composed of multiple widgets.
  160. :class:`~django.forms.widgets.MultiWidget` works hand in hand with the
  161. :class:`~django.forms.MultiValueField`.
  162. .. method:: render(name, value, attrs=None)
  163. Argument `value` is handled differently in this method from the
  164. subclasses of :class:`~Widget`.
  165. If `value` is a list, output of :meth:`~MultiWidget.render` will be a
  166. concatenation of rendered child widgets. If `value` is not a list, it
  167. will be first processed by the method :meth:`~MultiWidget.decompress()`
  168. to create the list and then processed as above.
  169. Unlike in the single value widgets, method :meth:`~MultiWidget.render`
  170. need not be implemented in the subclasses.
  171. .. method:: decompress(value)
  172. Returns a list of "decompressed" values for the given value of the
  173. multi-value field that makes use of the widget. The input value can be
  174. assumed as valid, but not necessarily non-empty.
  175. This method **must be implemented** by the subclass, and since the
  176. value may be empty, the implementation must be defensive.
  177. The rationale behind "decompression" is that it is necessary to "split"
  178. the combined value of the form field into the values of the individual
  179. field encapsulated within the multi-value field (e.g. when displaying
  180. the partially or fully filled-out form).
  181. .. tip::
  182. Note that :class:`~django.forms.MultiValueField` has a
  183. complementary method :meth:`~django.forms.MultiValueField.compress`
  184. with the opposite responsibility - to combine cleaned values of
  185. all member fields into one.
  186. .. _built-in widgets:
  187. Built-in widgets
  188. ----------------
  189. Django provides a representation of all the basic HTML widgets, plus some
  190. commonly used groups of widgets in the ``django.forms.widgets`` module,
  191. including :ref:`the input of text <text-widgets>`, :ref:`various checkboxes
  192. and selectors <selector-widgets>`, :ref:`uploading files <file-upload-widgets>`,
  193. and :ref:`handling of multi-valued input <composite-widgets>`.
  194. .. _text-widgets:
  195. Widgets handling input of text
  196. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  197. These widgets make use of the HTML elements ``input`` and ``textarea``.
  198. ``TextInput``
  199. ~~~~~~~~~~~~~
  200. .. class:: TextInput
  201. Text input: ``<input type='text' ...>``
  202. ``PasswordInput``
  203. ~~~~~~~~~~~~~~~~~
  204. .. class:: PasswordInput
  205. Password input: ``<input type='password' ...>``
  206. Takes one optional argument:
  207. .. attribute:: PasswordInput.render_value
  208. Determines whether the widget will have a value filled in when the
  209. form is re-displayed after a validation error (default is ``False``).
  210. .. versionchanged:: 1.3
  211. The default value for
  212. :attr:`~PasswordInput.render_value` was
  213. changed from ``True`` to ``False``
  214. ``HiddenInput``
  215. ~~~~~~~~~~~~~~~
  216. .. class:: HiddenInput
  217. Hidden input: ``<input type='hidden' ...>``
  218. Note that there also is a :class:`MultipleHiddenInput` widget that
  219. encapsulates a set of hidden input elements.
  220. ``DateInput``
  221. ~~~~~~~~~~~~~
  222. .. class:: DateInput
  223. Date input as a simple text box: ``<input type='text' ...>``
  224. Takes same arguments as :class:`TextInput`, with one more optional argument:
  225. .. attribute:: DateInput.format
  226. The format in which this field's initial value will be displayed.
  227. If no ``format`` argument is provided, the default format is the first
  228. format found in :setting:`DATE_INPUT_FORMATS` and respects
  229. :ref:`format-localization`.
  230. ``DateTimeInput``
  231. ~~~~~~~~~~~~~~~~~
  232. .. class:: DateTimeInput
  233. Date/time input as a simple text box: ``<input type='text' ...>``
  234. Takes same arguments as :class:`TextInput`, with one more optional argument:
  235. .. attribute:: DateTimeInput.format
  236. The format in which this field's initial value will be displayed.
  237. If no ``format`` argument is provided, the default format is the first
  238. format found in :setting:`DATETIME_INPUT_FORMATS` and respects
  239. :ref:`format-localization`.
  240. ``TimeInput``
  241. ~~~~~~~~~~~~~
  242. .. class:: TimeInput
  243. Time input as a simple text box: ``<input type='text' ...>``
  244. Takes same arguments as :class:`TextInput`, with one more optional argument:
  245. .. attribute:: TimeInput.format
  246. The format in which this field's initial value will be displayed.
  247. If no ``format`` argument is provided, the default format is the first
  248. format found in :setting:`TIME_INPUT_FORMATS` and respects
  249. :ref:`format-localization`.
  250. ``Textarea``
  251. ~~~~~~~~~~~~
  252. .. class:: Textarea
  253. Text area: ``<textarea>...</textarea>``
  254. .. _selector-widgets:
  255. Selector and checkbox widgets
  256. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  257. ``CheckboxInput``
  258. ~~~~~~~~~~~~~~~~~
  259. .. class:: CheckboxInput
  260. Checkbox: ``<input type='checkbox' ...>``
  261. Takes one optional argument:
  262. .. attribute:: CheckboxInput.check_test
  263. A callable that takes the value of the CheckBoxInput and returns
  264. ``True`` if the checkbox should be checked for that value.
  265. .. versionchanged:: 1.5
  266. Exceptions from ``check_test`` used to be silenced by its caller,
  267. this is no longer the case, they will propagate upwards.
  268. ``Select``
  269. ~~~~~~~~~~
  270. .. class:: Select
  271. Select widget: ``<select><option ...>...</select>``
  272. .. attribute:: Select.choices
  273. This attribute is optional when the field does not have a
  274. :attr:`~Field.choices` attribute. If it does, it will override anything
  275. you set here when the attribute is updated on the :class:`Field`.
  276. ``NullBooleanSelect``
  277. ~~~~~~~~~~~~~~~~~~~~~
  278. .. class:: NullBooleanSelect
  279. Select widget with options 'Unknown', 'Yes' and 'No'
  280. ``SelectMultiple``
  281. ~~~~~~~~~~~~~~~~~~
  282. .. class:: SelectMultiple
  283. Similar to :class:`Select`, but allows multiple selection:
  284. ``<select multiple='multiple'>...</select>``
  285. ``RadioSelect``
  286. ~~~~~~~~~~~~~~~
  287. .. class:: RadioSelect
  288. Similar to :class:`Select`, but rendered as a list of radio buttons within
  289. ``<li>`` tags:
  290. .. code-block:: html
  291. <ul>
  292. <li><input type='radio' ...></li>
  293. ...
  294. </ul>
  295. .. versionadded:: 1.4
  296. For more granular control over the generated markup, you can loop over the
  297. radio buttons in the template. Assuming a form ``myform`` with a field
  298. ``beatles`` that uses a ``RadioSelect`` as its widget:
  299. .. code-block:: html+django
  300. {% for radio in myform.beatles %}
  301. <div class="myradio">
  302. {{ radio }}
  303. </div>
  304. {% endfor %}
  305. This would generate the following HTML:
  306. .. code-block:: html
  307. <div class="myradio">
  308. <label><input type="radio" name="beatles" value="john" /> John</label>
  309. </div>
  310. <div class="myradio">
  311. <label><input type="radio" name="beatles" value="paul" /> Paul</label>
  312. </div>
  313. <div class="myradio">
  314. <label><input type="radio" name="beatles" value="george" /> George</label>
  315. </div>
  316. <div class="myradio">
  317. <label><input type="radio" name="beatles" value="ringo" /> Ringo</label>
  318. </div>
  319. That included the ``<label>`` tags. To get more granular, you can use each
  320. radio button's ``tag`` and ``choice_label`` attributes. For example, this template...
  321. .. code-block:: html+django
  322. {% for radio in myform.beatles %}
  323. <label>
  324. {{ radio.choice_label }}
  325. <span class="radio">{{ radio.tag }}</span>
  326. </label>
  327. {% endfor %}
  328. ...will result in the following HTML:
  329. .. code-block:: html
  330. <label>
  331. John
  332. <span class="radio"><input type="radio" name="beatles" value="john" /></span>
  333. </label>
  334. <label>
  335. Paul
  336. <span class="radio"><input type="radio" name="beatles" value="paul" /></span>
  337. </label>
  338. <label>
  339. George
  340. <span class="radio"><input type="radio" name="beatles" value="george" /></span>
  341. </label>
  342. <label>
  343. Ringo
  344. <span class="radio"><input type="radio" name="beatles" value="ringo" /></span>
  345. </label>
  346. If you decide not to loop over the radio buttons -- e.g., if your template simply includes
  347. ``{{ myform.beatles }}`` -- they'll be output in a ``<ul>`` with ``<li>`` tags, as above.
  348. ``CheckboxSelectMultiple``
  349. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  350. .. class:: CheckboxSelectMultiple
  351. Similar to :class:`SelectMultiple`, but rendered as a list of check
  352. buttons:
  353. .. code-block:: html
  354. <ul>
  355. <li><input type='checkbox' ...></li>
  356. ...
  357. </ul>
  358. .. _file-upload-widgets:
  359. File upload widgets
  360. ^^^^^^^^^^^^^^^^^^^
  361. ``FileInput``
  362. ~~~~~~~~~~~~~
  363. .. class:: FileInput
  364. File upload input: ``<input type='file' ...>``
  365. ``ClearableFileInput``
  366. ~~~~~~~~~~~~~~~~~~~~~~
  367. .. class:: ClearableFileInput
  368. .. versionadded:: 1.3
  369. File upload input: ``<input type='file' ...>``, with an additional checkbox
  370. input to clear the field's value, if the field is not required and has
  371. initial data.
  372. .. _composite-widgets:
  373. Composite widgets
  374. ^^^^^^^^^^^^^^^^^
  375. ``MultipleHiddenInput``
  376. ~~~~~~~~~~~~~~~~~~~~~~~
  377. .. class:: MultipleHiddenInput
  378. Multiple ``<input type='hidden' ...>`` widgets.
  379. A widget that handles multiple hidden widgets for fields that have a list
  380. of values.
  381. .. attribute:: MultipleHiddenInput.choices
  382. This attribute is optional when the field does not have a
  383. :attr:`~Field.choices` attribute. If it does, it will override anything
  384. you set here when the attribute is updated on the :class:`Field`.
  385. ``MultiWidget``
  386. ~~~~~~~~~~~~~~~
  387. .. class:: MultiWidget
  388. Wrapper around multiple other widgets. You'll probably want to use this
  389. class with :class:`MultiValueField`.
  390. Its ``render()`` method is different than other widgets', because it has to
  391. figure out how to split a single value for display in multiple widgets.
  392. Subclasses may implement ``format_output``, which takes the list of
  393. rendered widgets and returns a string of HTML that formats them any way
  394. you'd like.
  395. The ``value`` argument used when rendering can be one of two things:
  396. * A ``list``.
  397. * A single value (e.g., a string) that is the "compressed" representation
  398. of a ``list`` of values.
  399. In the second case -- i.e., if the value is *not* a list -- ``render()``
  400. will first decompress the value into a ``list`` before rendering it. It
  401. does so by calling the ``decompress()`` method, which
  402. :class:`MultiWidget`'s subclasses must implement. This method takes a
  403. single "compressed" value and returns a ``list``. An example of this is how
  404. :class:`SplitDateTimeWidget` turns a :class:`datetime` value into a list
  405. with date and time split into two seperate values::
  406. class SplitDateTimeWidget(MultiWidget):
  407. # ...
  408. def decompress(self, value):
  409. if value:
  410. return [value.date(), value.time().replace(microsecond=0)]
  411. return [None, None]
  412. When ``render()`` executes its HTML rendering, each value in the list is
  413. rendered with the corresponding widget -- the first value is rendered in
  414. the first widget, the second value is rendered in the second widget, etc.
  415. :class:`MultiWidget` has one required argument:
  416. .. attribute:: MultiWidget.widgets
  417. An iterable containing the widgets needed.
  418. ``SplitDateTimeWidget``
  419. ~~~~~~~~~~~~~~~~~~~~~~~
  420. .. class:: SplitDateTimeWidget
  421. Wrapper (using :class:`MultiWidget`) around two widgets: :class:`DateInput`
  422. for the date, and :class:`TimeInput` for the time.
  423. ``SplitDateTimeWidget`` has two optional attributes:
  424. .. attribute:: SplitDateTimeWidget.date_format
  425. Similar to :attr:`DateInput.format`
  426. .. attribute:: SplitDateTimeWidget.time_format
  427. Similar to :attr:`TimeInput.format`
  428. ``SplitHiddenDateTimeWidget``
  429. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  430. .. class:: SplitHiddenDateTimeWidget
  431. Similar to :class:`SplitDateTimeWidget`, but uses :class:`HiddenInput` for
  432. both date and time.
  433. .. currentmodule:: django.forms.extras.widgets
  434. ``SelectDateWidget``
  435. ~~~~~~~~~~~~~~~~~~~~
  436. .. class:: SelectDateWidget
  437. Wrapper around three :class:`~django.forms.Select` widgets: one each for
  438. month, day, and year. Note that this widget lives in a separate file from
  439. the standard widgets.
  440. Takes one optional argument:
  441. .. attribute:: SelectDateWidget.years
  442. An optional list/tuple of years to use in the "year" select box.
  443. The default is a list containing the current year and the next 9 years.