- fr
- Language: en
Widgets¶
A widget is Django’s representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget.
Tip
Widgets should not be confused with the form fields. Form fields deal with the logic of input validation and are used directly in templates. Widgets deal with rendering of HTML form input elements on the web page and extraction of raw submitted data. However, widgets do need to be assigned to form fields.
Specifying widgets¶
Whenever you specify a field on a form, Django will use a default widget that is appropriate to the type of data that is to be displayed. To find which widget is used on which field, see the documentation about Built-in Field classes.
However, if you want to use a different widget for a field, you can
just use the widget
argument on the field definition. For
example:
from django import forms
class CommentForm(forms.Form):
name = forms.CharField()
url = forms.URLField()
comment = forms.CharField(widget=forms.Textarea)
This would specify a form with a comment that uses a larger Textarea
widget, rather than the default TextInput
widget.
Setting arguments for widgets¶
Many widgets have optional extra arguments; they can be set when defining the
widget on the field. In the following example, the
years
attribute is set
for a SelectDateWidget
:
from django import forms
from django.forms.extras.widgets import SelectDateWidget
BIRTH_YEAR_CHOICES = ('1980', '1981', '1982')
FAVORITE_COLORS_CHOICES = (
('blue', 'Blue'),
('green', 'Green'),
('black', 'Black'),
)
class SimpleForm(forms.Form):
birth_year = forms.DateField(widget=SelectDateWidget(years=BIRTH_YEAR_CHOICES))
favorite_colors = forms.MultipleChoiceField(required=False,
widget=forms.CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES)
See the Built-in widgets for more information about which widgets are available and which arguments they accept.
Widgets inheriting from the Select widget¶
Widgets inheriting from the Select
widget deal with choices. They
present the user with a list of options to choose from. The different widgets
present this choice differently; the Select
widget itself uses a
<select>
HTML list representation, while RadioSelect
uses radio
buttons.
Select
widgets are used by default on ChoiceField
fields. The
choices displayed on the widget are inherited from the ChoiceField
and
changing ChoiceField.choices
will update Select.choices
. For
example:
>>> from django import forms
>>> CHOICES = (('1', 'First',), ('2', 'Second',))
>>> choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
>>> choice_field.choices
[('1', 'First'), ('2', 'Second')]
>>> choice_field.widget.choices
[('1', 'First'), ('2', 'Second')]
>>> choice_field.widget.choices = ()
>>> choice_field.choices = (('1', 'First and only',),)
>>> choice_field.widget.choices
[('1', 'First and only')]
Widgets which offer a choices
attribute can however be used
with fields which are not based on choice – such as a CharField
–
but it is recommended to use a ChoiceField
-based field when the
choices are inherent to the model and not just the representational widget.
Customizing widget instances¶
When Django renders a widget as HTML, it only renders very minimal markup -
Django doesn’t add class names, or any other widget-specific attributes. This
means, for example, that all TextInput
widgets will appear the same
on your Web pages.
There are two ways to customize widgets: per widget instance and per widget class.
Styling widget instances¶
If you want to make one widget instance look different from another, you will need to specify additional attributes at the time when the widget object is instantiated and assigned to a form field (and perhaps add some rules to your CSS files).
For example, take the following simple form:
from django import forms
class CommentForm(forms.Form):
name = forms.CharField()
url = forms.URLField()
comment = forms.CharField()
This form will include three default TextInput
widgets, with default
rendering – no CSS class, no extra attributes. This means that the input boxes
provided for each widget will be rendered exactly the same:
>>> f = CommentForm(auto_id=False)
>>> f.as_table()
<tr><th>Name:</th><td><input type="text" name="name" /></td></tr>
<tr><th>Url:</th><td><input type="url" name="url"/></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
On a real Web page, you probably don’t want every widget to look the same. You
might want a larger input element for the comment, and you might want the
‘name’ widget to have some special CSS class. It is also possible to specify
the ‘type’ attribute to take advantage of the new HTML5 input types. To do
this, you use the Widget.attrs
argument when creating the widget:
class CommentForm(forms.Form):
name = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))
url = forms.URLField()
comment = forms.CharField(widget=forms.TextInput(attrs={'size': '40'}))
Django will then include the extra attributes in the rendered output:
>>> f = CommentForm(auto_id=False)
>>> f.as_table()
<tr><th>Name:</th><td><input type="text" name="name" class="special"/></td></tr>
<tr><th>Url:</th><td><input type="url" name="url"/></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" size="40"/></td></tr>
You can also set the HTML id
using attrs
. See
BoundField.id_for_label
for an example.
Styling widget classes¶
With widgets, it is possible to add assets (css
and javascript
)
and more deeply customize their appearance and behavior.
In a nutshell, you will need to subclass the widget and either define a “Media” inner class or create a “media” property.
These methods involve somewhat advanced Python programming and are described in detail in the Form Assets topic guide.
Base Widget classes¶
Base widget classes Widget
and MultiWidget
are subclassed by
all the built-in widgets and may serve as a
foundation for custom widgets.
-
class
Widget
(attrs=None)[source]¶ This abstract class cannot be rendered, but provides the basic attribute
attrs
. You may also implement or override therender()
method on custom widgets.-
attrs
¶ A dictionary containing HTML attributes to be set on the rendered widget.
>>> from django import forms >>> name = forms.TextInput(attrs={'size': 10, 'title': 'Your name',}) >>> name.render('name', 'A name') '<input title="Your name" type="text" name="name" value="A name" size="10" />'
Changed in Django 1.8:If you assign a value of
True
orFalse
to an attribute, it will be rendered as an HTML5 boolean attribute:>>> name = forms.TextInput(attrs={'required': True}) >>> name.render('name', 'A name') '<input name="name" type="text" value="A name" required />' >>> >>> name = forms.TextInput(attrs={'required': False}) >>> name.render('name', 'A name') '<input name="name" type="text" value="A name" />'
-
render
(name, value, attrs=None)[source]¶ Returns HTML for the widget, as a Unicode string. This method must be implemented by the subclass, otherwise
NotImplementedError
will be raised.The ‘value’ given is not guaranteed to be valid input, therefore subclass implementations should program defensively.
-
value_from_datadict
(data, files, name)[source]¶ Given a dictionary of data and this widget’s name, returns the value of this widget.
files
may contain data coming fromrequest.FILES
. ReturnsNone
if a value wasn’t provided. Note also thatvalue_from_datadict
may be called more than once during handling of form data, so if you customize it and add expensive processing, you should implement some caching mechanism yourself.
-
-
class
MultiWidget
(widgets, attrs=None)[source]¶ A widget that is composed of multiple widgets.
MultiWidget
works hand in hand with theMultiValueField
.MultiWidget
has one required argument:-
widgets
¶ An iterable containing the widgets needed.
And one required method:
-
decompress
(value)[source]¶ This method takes a single “compressed” value from the field and returns a list of “decompressed” values. The input value can be assumed valid, but not necessarily non-empty.
This method must be implemented by the subclass, and since the value may be empty, the implementation must be defensive.
The rationale behind “decompression” is that it is necessary to “split” the combined value of the form field into the values for each widget.
An example of this is how
SplitDateTimeWidget
turns adatetime
value into a list with date and time split into two separate values:from django.forms import MultiWidget class SplitDateTimeWidget(MultiWidget): # ... def decompress(self, value): if value: return [value.date(), value.time().replace(microsecond=0)] return [None, None]
Tip
Note that
MultiValueField
has a complementary methodcompress()
with the opposite responsibility - to combine cleaned values of all member fields into one.
Other methods that may be useful to override include:
-
render
(name, value, attrs=None)[source]¶ Argument
value
is handled differently in this method from the subclasses ofWidget
because it has to figure out how to split a single value for display in multiple widgets.The
value
argument used when rendering can be one of two things:- A
list
. - A single value (e.g., a string) that is the “compressed” representation
of a
list
of values.
If
value
is a list, the output ofrender()
will be a concatenation of rendered child widgets. Ifvalue
is not a list, it will first be processed by the methoddecompress()
to create the list and then rendered.When
render()
executes its HTML rendering, each value in the list is rendered with the corresponding widget – the first value is rendered in the first widget, the second value is rendered in the second widget, etc.Unlike in the single value widgets, method
render()
need not be implemented in the subclasses.- A
-
format_output
(rendered_widgets)[source]¶ Given a list of rendered widgets (as strings), returns a Unicode string representing the HTML for the whole lot.
This hook allows you to format the HTML design of the widgets any way you’d like.
Here’s an example widget which subclasses
MultiWidget
to display a date with the day, month, and year in different select boxes. This widget is intended to be used with aDateField
rather than aMultiValueField
, thus we have implementedvalue_from_datadict()
:from datetime import date from django.forms import widgets class DateSelectorWidget(widgets.MultiWidget): def __init__(self, attrs=None): # create choices for days, months, years # example below, the rest snipped for brevity. years = [(year, year) for year in (2011, 2012, 2013)] _widgets = ( widgets.Select(attrs=attrs, choices=days), widgets.Select(attrs=attrs, choices=months), widgets.Select(attrs=attrs, choices=years), ) super(DateSelectorWidget, self).__init__(_widgets, attrs) def decompress(self, value): if value: return [value.day, value.month, value.year] return [None, None, None] def format_output(self, rendered_widgets): return ''.join(rendered_widgets) def value_from_datadict(self, data, files, name): datelist = [ widget.value_from_datadict(data, files, name + '_%s' % i) for i, widget in enumerate(self.widgets)] try: D = date( day=int(datelist[0]), month=int(datelist[1]), year=int(datelist[2]), ) except ValueError: return '' else: return str(D)
The constructor creates several
Select
widgets in a tuple. Thesuper
class uses this tuple to setup the widget.The
format_output()
method is fairly vanilla here (in fact, it’s the same as what’s been implemented as the default forMultiWidget
), but the idea is that you could add custom HTML between the widgets should you wish.The required method
decompress()
breaks up adatetime.date
value into the day, month, and year values corresponding to each widget. Note how the method handles the case wherevalue
isNone
.The default implementation of
value_from_datadict()
returns a list of values corresponding to eachWidget
. This is appropriate when using aMultiWidget
with aMultiValueField
, but since we want to use this widget with aDateField
which takes a single value, we have overridden this method to combine the data of all the subwidgets into adatetime.date
. The method extracts data from thePOST
dictionary and constructs and validates the date. If it is valid, we return the string, otherwise, we return an empty string which will causeform.is_valid
to returnFalse
.-
Built-in widgets¶
Django provides a representation of all the basic HTML widgets, plus some
commonly used groups of widgets in the django.forms.widgets
module,
including the input of text, various checkboxes
and selectors, uploading files,
and handling of multi-valued input.
Widgets handling input of text¶
These widgets make use of the HTML elements input
and textarea
.
NumberInput
¶
PasswordInput
¶
DateInput
¶
-
class
DateInput
[source]¶ Date input as a simple text box:
<input type='text' ...>
Takes same arguments as
TextInput
, with one more optional argument:-
format
¶ The format in which this field’s initial value will be displayed.
If no
format
argument is provided, the default format is the first format found inDATE_INPUT_FORMATS
and respects Format localization.-
DateTimeInput
¶
-
class
DateTimeInput
[source]¶ Date/time input as a simple text box:
<input type='text' ...>
Takes same arguments as
TextInput
, with one more optional argument:-
format
¶ The format in which this field’s initial value will be displayed.
If no
format
argument is provided, the default format is the first format found inDATETIME_INPUT_FORMATS
and respects Format localization.-
TimeInput
¶
-
class
TimeInput
[source]¶ Time input as a simple text box:
<input type='text' ...>
Takes same arguments as
TextInput
, with one more optional argument:-
format
¶ The format in which this field’s initial value will be displayed.
If no
format
argument is provided, the default format is the first format found inTIME_INPUT_FORMATS
and respects Format localization.-
Selector and checkbox widgets¶
CheckboxInput
¶
Select
¶
NullBooleanSelect
¶
SelectMultiple
¶
RadioSelect
¶
-
class
RadioSelect
[source]¶ Similar to
Select
, but rendered as a list of radio buttons within<li>
tags:<ul> <li><input type='radio' name='...'></li> ... </ul>
For more granular control over the generated markup, you can loop over the radio buttons in the template. Assuming a form
myform
with a fieldbeatles
that uses aRadioSelect
as its widget:{% for radio in myform.beatles %} <div class="myradio"> {{ radio }} </div> {% endfor %}
This would generate the following HTML:
<div class="myradio"> <label for="id_beatles_0"><input id="id_beatles_0" name="beatles" type="radio" value="john" /> John</label> </div> <div class="myradio"> <label for="id_beatles_1"><input id="id_beatles_1" name="beatles" type="radio" value="paul" /> Paul</label> </div> <div class="myradio"> <label for="id_beatles_2"><input id="id_beatles_2" name="beatles" type="radio" value="george" /> George</label> </div> <div class="myradio"> <label for="id_beatles_3"><input id="id_beatles_3" name="beatles" type="radio" value="ringo" /> Ringo</label> </div>
That included the
<label>
tags. To get more granular, you can use each radio button’stag
,choice_label
andid_for_label
attributes. For example, this template…{% for radio in myform.beatles %} <label for="{{ radio.id_for_label }}"> {{ radio.choice_label }} <span class="radio">{{ radio.tag }}</span> </label> {% endfor %}
…will result in the following HTML:
<label for="id_beatles_0"> John <span class="radio"><input id="id_beatles_0" name="beatles" type="radio" value="john" /></span> </label> <label for="id_beatles_1"> Paul <span class="radio"><input id="id_beatles_1" name="beatles" type="radio" value="paul" /></span> </label> <label for="id_beatles_2"> George <span class="radio"><input id="id_beatles_2" name="beatles" type="radio" value="george" /></span> </label> <label for="id_beatles_3"> Ringo <span class="radio"><input id="id_beatles_3" name="beatles" type="radio" value="ringo" /></span> </label>
If you decide not to loop over the radio buttons – e.g., if your template simply includes
{{ myform.beatles }}
– they’ll be output in a<ul>
with<li>
tags, as above.The outer
<ul>
container will receive theid
attribute defined on the widget.
When looping over the radio buttons, the label
and input
tags include
for
and id
attributes, respectively. Each radio button has an
id_for_label
attribute to output the element’s ID.
CheckboxSelectMultiple
¶
-
class
CheckboxSelectMultiple
[source]¶ Similar to
SelectMultiple
, but rendered as a list of check buttons:<ul> <li><input type='checkbox' name='...' ></li> ... </ul>
The outer
<ul>
container will receive theid
attribute defined on the widget.
Like RadioSelect
, you can now loop over the individual checkboxes making
up the lists. See the documentation of RadioSelect
for more details.
When looping over the checkboxes, the label
and input
tags include
for
and id
attributes, respectively. Each checkbox has an
id_for_label
attribute to output the element’s ID.
File upload widgets¶
Composite widgets¶
SplitDateTimeWidget
¶
-
class
SplitDateTimeWidget
[source]¶ Wrapper (using
MultiWidget
) around two widgets:DateInput
for the date, andTimeInput
for the time.SplitDateTimeWidget
has two optional attributes:-
date_format
¶ Similar to
DateInput.format
-
time_format
¶ Similar to
TimeInput.format
-
SelectDateWidget
¶
-
class
SelectDateWidget
[source]¶ Wrapper around three
Select
widgets: one each for month, day, and year. Note that this widget lives in a separate file from the standard widgets.Takes several optional arguments:
-
years
¶ An optional list/tuple of years to use in the “year” select box. The default is a list containing the current year and the next 9 years.
-
months
¶ - New in Django 1.7.
An optional dict of months to use in the “months” select box.
The keys of the dict correspond to the month number (1-indexed) and the values are the displayed months:
MONTHS = { 1:_('jan'), 2:_('feb'), 3:_('mar'), 4:_('apr'), 5:_('may'), 6:_('jun'), 7:_('jul'), 8:_('aug'), 9:_('sep'), 10:_('oct'), 11:_('nov'), 12:_('dec') }
-
empty_label
¶ - New in Django 1.8.
If the
DateField
is not required,SelectDateWidget
will have an empty choice at the top of the list (which is---
by default). You can change the text of this label with theempty_label
attribute.empty_label
can be astring
,list
, ortuple
. When a string is used, all select boxes will each have an empty choice with this label. Ifempty_label
is alist
ortuple
of 3 string elements, the select boxes will have their own custom label. The labels should be in this order('year_label', 'month_label', 'day_label')
.# A custom empty label with string field1 = forms.DateField(widget=SelectDateWidget(empty_label="Nothing")) # A custom empty label with tuple field1 = forms.DateField( widget=SelectDateWidget( empty_label=("Choose Year", "Choose Month", "Choose Day"), ), )
-