widgets.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. Specifying widgets
  11. ------------------
  12. Whenever you specify a field on a form, Django will use a default widget
  13. that is appropriate to the type of data that is to be displayed. To find
  14. which widget is used on which field, see the documentation about
  15. :ref:`built-in fields`.
  16. However, if you want to use a different widget for a field, you can
  17. just use the :attr:`~Field.widget` argument on the field definition. For
  18. example::
  19. from django import forms
  20. class CommentForm(forms.Form):
  21. name = forms.CharField()
  22. url = forms.URLField()
  23. comment = forms.CharField(widget=forms.Textarea)
  24. This would specify a form with a comment that uses a larger :class:`Textarea`
  25. widget, rather than the default :class:`TextInput` widget.
  26. Setting arguments for widgets
  27. -----------------------------
  28. Many widgets have optional extra arguments; they can be set when defining the
  29. widget on the field. In the following example, the
  30. :attr:`~SelectDateWidget.years` attribute is set for a
  31. :class:`~django.forms.extras.widgets.SelectDateWidget`::
  32. from django.forms.fields import DateField, ChoiceField, MultipleChoiceField
  33. from django.forms.widgets import RadioSelect, CheckboxSelectMultiple
  34. from django.forms.extras.widgets import SelectDateWidget
  35. BIRTH_YEAR_CHOICES = ('1980', '1981', '1982')
  36. GENDER_CHOICES = (('m', 'Male'), ('f', 'Female'))
  37. FAVORITE_COLORS_CHOICES = (('blue', 'Blue'),
  38. ('green', 'Green'),
  39. ('black', 'Black'))
  40. class SimpleForm(forms.Form):
  41. birth_year = DateField(widget=SelectDateWidget(years=BIRTH_YEAR_CHOICES))
  42. gender = ChoiceField(widget=RadioSelect, choices=GENDER_CHOICES)
  43. favorite_colors = forms.MultipleChoiceField(required=False,
  44. widget=CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES)
  45. See the :ref:`built-in widgets` for more information about which widgets
  46. are available and which arguments they accept.
  47. Widgets inheriting from the Select widget
  48. -----------------------------------------
  49. Widgets inheriting from the :class:`Select` widget deal with choices. They
  50. present the user with a list of options to choose from. The different widgets
  51. present this choice differently; the :class:`Select` widget itself uses a
  52. ``<select>`` HTML list representation, while :class:`RadioSelect` uses radio
  53. buttons.
  54. :class:`Select` widgets are used by default on :class:`ChoiceField` fields. The
  55. choices displayed on the widget are inherited from the :class:`ChoiceField` and
  56. changing :attr:`ChoiceField.choices` will update :attr:`Select.choices`. For
  57. example::
  58. >>> from django import forms
  59. >>> CHOICES = (('1', 'First',), ('2', 'Second',)))
  60. >>> choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
  61. >>> choice_field.choices
  62. [('1', 'First'), ('2', 'Second')]
  63. >>> choice_field.widget.choices
  64. [('1', 'First'), ('2', 'Second')]
  65. >>> choice_field.widget.choices = ()
  66. >>> choice_field.choices = (('1', 'First and only',),)
  67. >>> choice_field.widget.choices
  68. [('1', 'First and only')]
  69. Widgets which offer a :attr:`~Select.choices` attribute can however be used
  70. with fields which are not based on choice -- such as a :class:`CharField` --
  71. but it is recommended to use a :class:`ChoiceField`-based field when the
  72. choices are inherent to the model and not just the representational widget.
  73. Customizing widget instances
  74. ----------------------------
  75. When Django renders a widget as HTML, it only renders the bare minimum
  76. HTML - Django doesn't add a class definition, or any other widget-specific
  77. attributes. This means that all :class:`TextInput` widgets will appear the same
  78. on your Web page.
  79. If you want to make one widget look different to another, you need to
  80. specify additional attributes for each widget. When you specify a
  81. widget, you can provide a list of attributes that will be added to the
  82. rendered HTML for the widget.
  83. For example, take the following simple form::
  84. from django import forms
  85. class CommentForm(forms.Form):
  86. name = forms.CharField()
  87. url = forms.URLField()
  88. comment = forms.CharField()
  89. This form will include three default :class:`TextInput` widgets, with default
  90. rendering -- no CSS class, no extra attributes. This means that the input boxes
  91. provided for each widget will be rendered exactly the same::
  92. >>> f = CommentForm(auto_id=False)
  93. >>> f.as_table()
  94. <tr><th>Name:</th><td><input type="text" name="name" /></td></tr>
  95. <tr><th>Url:</th><td><input type="text" name="url"/></td></tr>
  96. <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
  97. On a real Web page, you probably don't want every widget to look the same. You
  98. might want a larger input element for the comment, and you might want the
  99. 'name' widget to have some special CSS class. To do this, you use the
  100. :attr:`Widget.attrs` argument when creating the widget:
  101. For example::
  102. class CommentForm(forms.Form):
  103. name = forms.CharField(
  104. widget=forms.TextInput(attrs={'class':'special'}))
  105. url = forms.URLField()
  106. comment = forms.CharField(
  107. widget=forms.TextInput(attrs={'size':'40'}))
  108. Django will then include the extra attributes in the rendered output:
  109. >>> f = CommentForm(auto_id=False)
  110. >>> f.as_table()
  111. <tr><th>Name:</th><td><input type="text" name="name" class="special"/></td></tr>
  112. <tr><th>Url:</th><td><input type="text" name="url"/></td></tr>
  113. <tr><th>Comment:</th><td><input type="text" name="comment" size="40"/></td></tr>
  114. .. _built-in widgets:
  115. Built-in widgets
  116. ----------------
  117. Django provides a representation of all the basic HTML widgets, plus some
  118. commonly used groups of widgets:
  119. ``Widget``
  120. ~~~~~~~~~~
  121. .. class:: Widget
  122. This abstract class cannot be rendered, but provides the basic attribute :attr:`~Widget.attrs`.
  123. .. attribute:: Widget.attrs
  124. A dictionary containing HTML attributes to be set on the rendered widget.
  125. .. code-block:: python
  126. >>> name = forms.TextInput(attrs={'size': 10, 'title': 'Your name',})
  127. >>> name.render('name', 'A name')
  128. u'<input title="Your name" type="text" name="name" value="A name" size="10" />'
  129. ``TextInput``
  130. ~~~~~~~~~~~~~
  131. .. class:: TextInput
  132. Text input: ``<input type='text' ...>``
  133. ``PasswordInput``
  134. ~~~~~~~~~~~~~~~~~
  135. .. class:: PasswordInput
  136. Password input: ``<input type='password' ...>``
  137. Takes one optional argument:
  138. .. attribute:: PasswordInput.render_value
  139. Determines whether the widget will have a value filled in when the
  140. form is re-displayed after a validation error (default is ``False``).
  141. .. versionchanged:: 1.3
  142. The default value for
  143. :attr:`~PasswordInput.render_value` was
  144. changed from ``True`` to ``False``
  145. ``HiddenInput``
  146. ~~~~~~~~~~~~~~~
  147. .. class:: HiddenInput
  148. Hidden input: ``<input type='hidden' ...>``
  149. ``MultipleHiddenInput``
  150. ~~~~~~~~~~~~~~~~~~~~~~~
  151. .. class:: MultipleHiddenInput
  152. Multiple ``<input type='hidden' ...>`` widgets.
  153. A widget that handles multiple hidden widgets for fields that have a list
  154. of values.
  155. .. attribute:: MultipleHiddenInput.choices
  156. This attribute is optional when the field does not have a
  157. :attr:`~Field.choices` attribute. If it does, it will override anything
  158. you set here when the attribute is updated on the :class:`Field`.
  159. ``FileInput``
  160. ~~~~~~~~~~~~~
  161. .. class:: FileInput
  162. File upload input: ``<input type='file' ...>``
  163. ``ClearableFileInput``
  164. ~~~~~~~~~~~~~~~~~~~~~~
  165. .. class:: ClearableFileInput
  166. .. versionadded:: 1.3
  167. File upload input: ``<input type='file' ...>``, with an additional checkbox
  168. input to clear the field's value, if the field is not required and has
  169. initial data.
  170. ``DateInput``
  171. ~~~~~~~~~~~~~
  172. .. class:: DateInput
  173. Date input as a simple text box: ``<input type='text' ...>``
  174. Takes one optional argument:
  175. .. attribute:: DateInput.format
  176. The format in which this field's initial value will be displayed.
  177. If no ``format`` argument is provided, the default format is the first
  178. format found in :setting:`DATE_INPUT_FORMATS` and respects
  179. :ref:`format-localization`.
  180. ``DateTimeInput``
  181. ~~~~~~~~~~~~~~~~~
  182. .. class:: DateTimeInput
  183. Date/time input as a simple text box: ``<input type='text' ...>``
  184. Takes one optional argument:
  185. .. attribute:: DateTimeInput.format
  186. The format in which this field's initial value will be displayed.
  187. If no ``format`` argument is provided, the default format is the first
  188. format found in :setting:`DATETIME_INPUT_FORMATS` and respects
  189. :ref:`format-localization`.
  190. ``TimeInput``
  191. ~~~~~~~~~~~~~
  192. .. class:: TimeInput
  193. Time input as a simple text box: ``<input type='text' ...>``
  194. Takes one optional argument:
  195. .. attribute:: TimeInput.format
  196. The format in which this field's initial value will be displayed.
  197. If no ``format`` argument is provided, the default format is the first
  198. format found in :setting:`TIME_INPUT_FORMATS` and respects
  199. :ref:`format-localization`.
  200. ``Textarea``
  201. ~~~~~~~~~~~~
  202. .. class:: Textarea
  203. Text area: ``<textarea>...</textarea>``
  204. ``CheckboxInput``
  205. ~~~~~~~~~~~~~~~~~
  206. .. class:: CheckboxInput
  207. Checkbox: ``<input type='checkbox' ...>``
  208. Takes one optional argument:
  209. .. attribute:: CheckboxInput.check_test
  210. A callable that takes the value of the CheckBoxInput and returns
  211. ``True`` if the checkbox should be checked for that value.
  212. ``Select``
  213. ~~~~~~~~~~
  214. .. class:: Select
  215. Select widget: ``<select><option ...>...</select>``
  216. .. attribute:: Select.choices
  217. This attribute is optional when the field does not have a
  218. :attr:`~Field.choices` attribute. If it does, it will override anything
  219. you set here when the attribute is updated on the :class:`Field`.
  220. ``NullBooleanSelect``
  221. ~~~~~~~~~~~~~~~~~~~~~
  222. .. class:: NullBooleanSelect
  223. Select widget with options 'Unknown', 'Yes' and 'No'
  224. ``SelectMultiple``
  225. ~~~~~~~~~~~~~~~~~~
  226. .. class:: SelectMultiple
  227. Similar to :class:`Select`, but allows multiple selection:
  228. ``<select multiple='multiple'>...</select>``
  229. ``RadioSelect``
  230. ~~~~~~~~~~~~~~~
  231. .. class:: RadioSelect
  232. Similar to :class:`Select`, but rendered as a list of radio buttons:
  233. .. code-block:: html
  234. <ul>
  235. <li><input type='radio' ...></li>
  236. ...
  237. </ul>
  238. ``CheckboxSelectMultiple``
  239. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  240. .. class:: CheckboxSelectMultiple
  241. Similar to :class:`SelectMultiple`, but rendered as a list of check
  242. buttons:
  243. .. code-block:: html
  244. <ul>
  245. <li><input type='checkbox' ...></li>
  246. ...
  247. </ul>
  248. ``MultiWidget``
  249. ~~~~~~~~~~~~~~~
  250. .. class:: MultiWidget
  251. Wrapper around multiple other widgets. You'll probably want to use this
  252. class with :class:`MultiValueField`.
  253. Its ``render()`` method is different than other widgets', because it has to
  254. figure out how to split a single value for display in multiple widgets.
  255. Subclasses may implement ``format_output``, which takes the list of
  256. rendered widgets and returns a string of HTML that formats them any way
  257. you'd like.
  258. The ``value`` argument used when rendering can be one of two things:
  259. * A ``list``.
  260. * A single value (e.g., a string) that is the "compressed" representation
  261. of a ``list`` of values.
  262. In the second case -- i.e., if the value is *not* a list -- ``render()``
  263. will first decompress the value into a ``list`` before rendering it. It
  264. does so by calling the ``decompress()`` method, which
  265. :class:`MultiWidget`'s subclasses must implement. This method takes a
  266. single "compressed" value and returns a ``list``. An example of this is how
  267. :class:`SplitDateTimeWidget` turns a :class:`datetime` value into a list
  268. with date and time split into two seperate values::
  269. class SplitDateTimeWidget(MultiWidget):
  270. # ...
  271. def decompress(self, value):
  272. if value:
  273. return [value.date(), value.time().replace(microsecond=0)]
  274. return [None, None]
  275. When ``render()`` executes its HTML rendering, each value in the list is
  276. rendered with the corresponding widget -- the first value is rendered in
  277. the first widget, the second value is rendered in the second widget, etc.
  278. :class:`MultiWidget` has one required argument:
  279. .. attribute:: MultiWidget.widgets
  280. An iterable containing the widgets needed.
  281. ``SplitDateTimeWidget``
  282. ~~~~~~~~~~~~~~~~~~~~~~~
  283. .. class:: SplitDateTimeWidget
  284. Wrapper (using :class:`MultiWidget`) around two widgets: :class:`DateInput`
  285. for the date, and :class:`TimeInput` for the time.
  286. ``SplitDateTimeWidget`` has two optional attributes:
  287. .. attribute:: SplitDateTimeWidget.date_format
  288. Similar to :attr:`DateInput.format`
  289. .. attribute:: SplitDateTimeWidget.time_format
  290. Similar to :attr:`TimeInput.format`
  291. ``SplitHiddenDateTimeWidget``
  292. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  293. .. class:: SplitHiddenDateTimeWidget
  294. Similar to :class:`SplitDateTimeWidget`, but uses :class:`HiddenInput` for
  295. both date and time.
  296. .. currentmodule:: django.forms.extras.widgets
  297. ``SelectDateWidget``
  298. ~~~~~~~~~~~~~~~~~~~~
  299. .. class:: SelectDateWidget
  300. Wrapper around three :class:`~django.forms.Select` widgets: one each for
  301. month, day, and year. Note that this widget lives in a separate file from
  302. the standard widgets.
  303. Takes one optional argument:
  304. .. attribute:: SelectDateWidget.years
  305. An optional list/tuple of years to use in the "year" select box.
  306. The default is a list containing the current year and the next 9 years.