Widgets¶
A widget is Django’s representation of an HTML input element. The widgethandles the rendering of the HTML, and the extraction of data from a GET/POSTdictionary that corresponds to the widget.
The HTML generated by the built-in widgets uses HTML5 syntax, targeting<!DOCTYPEhtml>
. For example, it uses boolean attributes such aschecked
rather than the XHTML style ofchecked='checked'
.
Tip
Widgets should not be confused with theform fields.Form fields deal with the logic of input validation and are used directlyin templates. Widgets deal with rendering of HTML form input elements onthe web page and extraction of raw submitted data. However, widgets doneed to beassigned to form fields.
Specifying widgets¶
Whenever you specify a field on a form, Django will use a default widgetthat is appropriate to the type of data that is to be displayed. To findwhich widget is used on which field, see the documentation aboutBuilt-in Field classes.
However, if you want to use a different widget for a field, you canuse thewidget
argument on the field definition. For example:
fromdjangoimportformsclassCommentForm(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 largerTextarea
widget, rather than the defaultTextInput
widget.
Setting arguments for widgets¶
Many widgets have optional extra arguments; they can be set when defining thewidget on the field. In the following example, theyears
attribute is set for aSelectDateWidget
:
fromdjangoimportformsBIRTH_YEAR_CHOICES=["1980","1981","1982"]FAVORITE_COLORS_CHOICES={"blue":"Blue","green":"Green","black":"Black",}classSimpleForm(forms.Form):birth_year=forms.DateField(widget=forms.SelectDateWidget(years=BIRTH_YEAR_CHOICES))favorite_colors=forms.MultipleChoiceField(required=False,widget=forms.CheckboxSelectMultiple,choices=FAVORITE_COLORS_CHOICES,)
See theBuilt-in widgets for more information about which widgetsare available and which arguments they accept.
Widgets inheriting from theSelect
widget¶
Widgets inheriting from theSelect
widget deal with choices. Theypresent the user with a list of options to choose from. The different widgetspresent this choice differently; theSelect
widget itself uses a<select>
HTML list representation, whileRadioSelect
uses radiobuttons.
Select
widgets are used by default onChoiceField
fields. Thechoices displayed on the widget are inherited from theChoiceField
andchangingChoiceField.choices
will updateSelect.choices
. Forexample:
>>>fromdjangoimportforms>>>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 achoices
attribute can however be usedwith fields which are not based on choice – such as aCharField
–but it is recommended to use aChoiceField
-based field when thechoices 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. Thismeans, for example, that allTextInput
widgets will appear the sameon your web pages.
There are two ways to customize widgets:per widget instance andper widget class.
Styling widget instances¶
If you want to make one widget instance look different from another, you willneed to specify additional attributes at the time when the widget object isinstantiated and assigned to a form field (and perhaps add some rules to yourCSS files).
For example, take the following form:
fromdjangoimportformsclassCommentForm(forms.Form):name=forms.CharField()url=forms.URLField()comment=forms.CharField()
This form will include three defaultTextInput
widgets, with defaultrendering – no CSS class, no extra attributes. This means that the input boxesprovided for each widget will be rendered exactly the same:
>>>f=CommentForm(auto_id=False)>>>print(f)<div>Name:<input type="text" name="name" required></div><div>Url:<input type="url" name="url" required></div><div>Comment:<input type="text" name="comment" required></div>
On a real web page, you probably don’t want every widget to look the same. Youmight 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 specifythe ‘type’ attribute to take advantage of the new HTML5 input types. To dothis, you use theWidget.attrs
argument when creating the widget:
classCommentForm(forms.Form):name=forms.CharField(widget=forms.TextInput(attrs={"class":"special"}))url=forms.URLField()comment=forms.CharField(widget=forms.TextInput(attrs={"size":"40"}))
You can also modify a widget in the form definition:
classCommentForm(forms.Form):name=forms.CharField()url=forms.URLField()comment=forms.CharField()name.widget.attrs.update({"class":"special"})comment.widget.attrs.update(size="40")
Or if the field isn’t declared directly on the form (such as model form fields),you can use theForm.fields
attribute:
classCommentForm(forms.ModelForm):def__init__(self,*args,**kwargs):super().__init__(*args,**kwargs)self.fields["name"].widget.attrs.update({"class":"special"})self.fields["comment"].widget.attrs.update(size="40")
Django will then include the extra attributes in the rendered output:
>>>f=CommentForm(auto_id=False)>>>print(f)<div>Name:<input type="text" name="name" class="special" required></div><div>Url:<input type="url" name="url" required></div><div>Comment:<input type="text" name="comment" size="40" required></div>
You can also set the HTMLid
usingattrs
. SeeBoundField.id_for_label
for an example.
Styling widget classes¶
With widgets, it is possible to add assets (css
andjavascript
)and more deeply customize their appearance and behavior.
In a nutshell, you will need to subclass the widget and eitherdefine a “Media” inner class orcreate a “media” property.
These methods involve somewhat advanced Python programming and are described indetail in theForm Assets topic guide.
Base widget classes¶
Base widget classesWidget
andMultiWidget
are subclassed byall thebuilt-in widgets and may serve as afoundation for custom widgets.
Widget
¶
- class
Widget
(attrs=None)¶ 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 renderedwidget.
>>>fromdjangoimportforms>>>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">'
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">'
supports_microseconds
¶An attribute that defaults to
True
. If set toFalse
, themicroseconds part ofdatetime
andtime
values will be set to0
.
format_value
(value)¶Cleans and returns a value for use in the widget template.
value
isn’t guaranteed to be valid input, therefore subclass implementationsshould program defensively.
get_context
(name,value,attrs)¶Returns a dictionary of values to use when rendering the widgettemplate. By default, the dictionary contains a single key,
'widget'
, which is a dictionary representation of the widgetcontaining the following keys:'name'
: The name of the field from thename
argument.'is_hidden'
: A boolean indicating whether or not this widget ishidden.'required'
: A boolean indicating whether or not the field forthis widget is required.'value'
: The value as returned byformat_value()
.'attrs'
: HTML attributes to be set on the rendered widget. Thecombination of theattrs
attribute and theattrs
argument.'template_name'
: The value ofself.template_name
.
Widget
subclasses can provide custom context values by overridingthis method.
id_for_label
(id_)¶Returns the HTML ID attribute of this widget for use by a
<label>
,given the ID of the field. Returns an empty string if an ID isn’tavailable.This hook is necessary because some widgets have multiple HTMLelements and, thus, multiple IDs. In that case, this method shouldreturn an ID value that corresponds to the first ID in the widget’stags.
render
(name,value,attrs=None,renderer=None)¶Renders a widget to HTML using the given renderer. If
renderer
isNone
, the renderer from theFORM_RENDERER
setting isused.
value_from_datadict
(data,files,name)¶Given a dictionary of data and this widget’s name, returns the valueof this widget.
files
may contain data coming fromrequest.FILES
. ReturnsNone
if a value wasn’t provided. Note also thatvalue_from_datadict
maybe called more than once during handling of form data, so if youcustomize it and add expensive processing, you should implement somecaching mechanism yourself.
value_omitted_from_data
(data,files,name)¶Given
data
andfiles
dictionaries and this widget’s name,returns whether or not there’s data or files for the widget.The method’s result affects whether or not a field in a model formfalls back to its default.
Special cases are
CheckboxInput
,CheckboxSelectMultiple
, andSelectMultiple
, which always returnFalse
because an unchecked checkbox and unselected<selectmultiple>
don’t appear in the data of an HTML formsubmission, so it’s unknown whether or not the user submitted a value.
use_fieldset
¶An attribute to identify if the widget should be grouped in a
<fieldset>
with a<legend>
when rendered. Defaults toFalse
but isTrue
when the widget contains multiple<input>
tags such asCheckboxSelectMultiple
,RadioSelect
,MultiWidget
,SplitDateTimeWidget
, andSelectDateWidget
.
use_required_attribute
(initial)¶Given a form field’s
initial
value, returns whether or not thewidget can be rendered with therequired
HTML attribute. Forms usethis method along withField.required
andForm.use_required_attribute
to determine whether or notto display therequired
attribute for each field.By default, returns
False
for hidden widgets andTrue
otherwise. Special cases areFileInput
andClearableFileInput
, which returnFalse
wheninitial
is set, andCheckboxSelectMultiple
,which always returnsFalse
because browser validation would requireall checkboxes to be checked instead of at least one.Override this method in custom widgets that aren’t compatible withbrowser validation. For example, a WSYSIWG text editor widget backed bya hidden
textarea
element may want to always returnFalse
toavoid browser validation on the hidden field.
MultiWidget
¶
- class
MultiWidget
(widgets,attrs=None)¶ 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. For example:
>>>fromdjango.formsimportMultiWidget,TextInput>>>widget=MultiWidget(widgets=[TextInput,TextInput])>>>widget.render("name",["john","paul"])'<input type="text" name="name_0" value="john"><input type="text" name="name_1" value="paul">'
You may provide a dictionary in order to specify custom suffixes forthe
name
attribute on each subwidget. In this case, for each(key,widget)
pair, the key will be appended to thename
of thewidget in order to generate the attribute value. You may provide theempty string (''
) for a single key, in order to suppress the suffixfor one widget. For example:>>>widget=MultiWidget(widgets={"":TextInput,"last":TextInput})>>>widget.render("name",["john","paul"])'<input type="text" name="name" value="john"><input type="text" name="name_last" value="paul">'
And one required method:
decompress
(value)¶This method takes a single “compressed” value from the field andreturns a list of “decompressed” values. The input value can beassumed valid, but not necessarily non-empty.
This methodmust be implemented by the subclass, and since thevalue 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 splitinto two separate values:fromdjango.formsimportMultiWidgetclassSplitDateTimeWidget(MultiWidget):# ...defdecompress(self,value):ifvalue:return[value.date(),value.time()]return[None,None]
Tip
Note that
MultiValueField
has acomplementary methodcompress()
with the opposite responsibility - to combine cleaned values ofall member fields into one.
It provides some custom context:
get_context
(name,value,attrs)¶In addition to the
'widget'
key described inWidget.get_context()
,MultiWidget
adds awidget['subwidgets']
key.These can be looped over in the widget template:
{%forsubwidgetinwidget.subwidgets%}{%includesubwidget.template_namewithwidget=subwidget%}{%endfor%}
Here’s an example widget which subclasses
MultiWidget
to displaya date with the day, month, and year in different select boxes. This widgetis intended to be used with aDateField
rather thanaMultiValueField
, thus we have implementedvalue_from_datadict()
:fromdatetimeimportdatefromdjangoimportformsclassDateSelectorWidget(forms.MultiWidget):def__init__(self,attrs=None):days={day:dayfordayinrange(1,32)}months={month:monthformonthinrange(1,13)}years={year:yearforyearin[2018,2019,2020]}widgets=[forms.Select(attrs=attrs,choices=days),forms.Select(attrs=attrs,choices=months),forms.Select(attrs=attrs,choices=years),]super().__init__(widgets,attrs)defdecompress(self,value):ifisinstance(value,date):return[value.day,value.month,value.year]elifisinstance(value,str):year,month,day=value.split("-")return[day,month,year]return[None,None,None]defvalue_from_datadict(self,data,files,name):day,month,year=super().value_from_datadict(data,files,name)# DateField expects a single string that it can parse into a date.return"{}-{}-{}".format(year,month,day)
The constructor creates several
Select
widgets in a list. Thesuper()
method uses this list to set up the widget.The required method
decompress()
breaks up adatetime.date
value into the day, month, and year values correspondingto each widget. If an invalid date was selected, such as the non-existent30th February, theDateField
passes this method astring instead, so that needs parsing. The finalreturn
handles whenvalue
isNone
, meaning we don’t have any defaults for oursubwidgets.The default implementation of
value_from_datadict()
returns alist of values corresponding to eachWidget
. This is appropriate whenusing aMultiWidget
with aMultiValueField
. Butsince we want to use this widget with aDateField
,which takes a single value, we have overridden this method. Theimplementation here combines the data from the subwidgets into a string inthe format thatDateField
expects.
Built-in widgets¶
Django provides a representation of all the basic HTML widgets, plus somecommonly used groups of widgets in thedjango.forms.widgets
module,includingthe input of text,various checkboxesand selectors,uploading files,andhandling of multi-valued input.
Widgets handling input of text¶
These widgets make use of the HTML elementsinput
andtextarea
.
TextInput
¶
- class
TextInput
¶ input_type
:'text'
template_name
:'django/forms/widgets/text.html'
- Renders as:
<inputtype="text"...>
NumberInput
¶
EmailInput
¶
- class
EmailInput
¶ input_type
:'email'
template_name
:'django/forms/widgets/email.html'
- Renders as:
<inputtype="email"...>
URLInput
¶
- class
URLInput
¶ input_type
:'url'
template_name
:'django/forms/widgets/url.html'
- Renders as:
<inputtype="url"...>
PasswordInput
¶
HiddenInput
¶
- class
HiddenInput
¶ input_type
:'hidden'
template_name
:'django/forms/widgets/hidden.html'
- Renders as:
<inputtype="hidden"...>
Note that there also is a
MultipleHiddenInput
widget thatencapsulates a set of hidden input elements.
DateInput
¶
- class
DateInput
¶ input_type
:'text'
template_name
:'django/forms/widgets/date.html'
- Renders as:
<inputtype="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 firstformat found inDATE_INPUT_FORMATS
and respectsFormat localization.%U
,%W
, and%j
formats are notsupported by this widget.
DateTimeInput
¶
- class
DateTimeInput
¶ input_type
:'text'
template_name
:'django/forms/widgets/datetime.html'
- Renders as:
<inputtype="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 firstformat found inDATETIME_INPUT_FORMATS
and respectsFormat localization.%U
,%W
, and%j
formats are notsupported by this widget.By default, the microseconds part of the time value is always set to
0
.If microseconds are required, use a subclass with thesupports_microseconds
attribute set toTrue
.
TimeInput
¶
- class
TimeInput
¶ input_type
:'text'
template_name
:'django/forms/widgets/time.html'
- Renders as:
<inputtype="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 firstformat found inTIME_INPUT_FORMATS
and respectsFormat localization.For the treatment of microseconds, see
DateTimeInput
.
Selector and checkbox widgets¶
These widgets make use of the HTML elements<select>
,<inputtype="checkbox">
, and<inputtype="radio">
.
Widgets that render multiple choices have anoption_template_name
attributethat specifies the template used to render each choice. For example, for theSelect
widget,select_option.html
renders the<option>
for a<select>
.
CheckboxInput
¶
Select
¶
- class
Select
¶ template_name
:'django/forms/widgets/select.html'
option_template_name
:'django/forms/widgets/select_option.html'
- Renders as:
<select><option...>...</select>
NullBooleanSelect
¶
- class
NullBooleanSelect
¶ template_name
:'django/forms/widgets/select.html'
option_template_name
:'django/forms/widgets/select_option.html'
Select widget with options ‘Unknown’, ‘Yes’ and ‘No’
SelectMultiple
¶
RadioSelect
¶
- class
RadioSelect
¶ template_name
:'django/forms/widgets/radio.html'
option_template_name
:'django/forms/widgets/radio_option.html'
Similar to
Select
, but rendered as a list of radio buttons within<div>
tags:<div><div><inputtype="radio"name="..."></div> ...</div>
For more granular control over the generated markup, you can loop over theradio buttons in the template. Assuming a form
myform
with a fieldbeatles
that uses aRadioSelect
as its widget:<fieldset><legend>{{myform.beatles.label}}</legend>{%forradioinmyform.beatles%}<divclass="myradio">{{radio}}</div>{%endfor%}</fieldset>
This would generate the following HTML:
<fieldset><legend>Radio buttons</legend><divclass="myradio"><labelfor="id_beatles_0"><inputid="id_beatles_0"name="beatles"type="radio"value="john"required> John</label></div><divclass="myradio"><labelfor="id_beatles_1"><inputid="id_beatles_1"name="beatles"type="radio"value="paul"required> Paul</label></div><divclass="myradio"><labelfor="id_beatles_2"><inputid="id_beatles_2"name="beatles"type="radio"value="george"required> George</label></div><divclass="myradio"><labelfor="id_beatles_3"><inputid="id_beatles_3"name="beatles"type="radio"value="ringo"required> Ringo</label></div></fieldset>
That included the
<label>
tags. To get more granular, you can use eachradio button’stag
,choice_label
andid_for_label
attributes.For example, this template…<fieldset><legend>{{myform.beatles.label}}</legend>{%forradioinmyform.beatles%}<labelfor="{{radio.id_for_label}}">{{radio.choice_label}}<spanclass="radio">{{radio.tag}}</span></label>{%endfor%}</fieldset>
…will result in the following HTML:
<fieldset><legend>Radio buttons</legend><labelfor="id_beatles_0"> John<spanclass="radio"><inputid="id_beatles_0"name="beatles"type="radio"value="john"required></span></label><labelfor="id_beatles_1"> Paul<spanclass="radio"><inputid="id_beatles_1"name="beatles"type="radio"value="paul"required></span></label><labelfor="id_beatles_2"> George<spanclass="radio"><inputid="id_beatles_2"name="beatles"type="radio"value="george"required></span></label><labelfor="id_beatles_3"> Ringo<spanclass="radio"><inputid="id_beatles_3"name="beatles"type="radio"value="ringo"required></span></label></fieldset>
If you decide not to loop over the radio buttons – e.g., if your templateincludes
{{myform.beatles}}
– they’ll be output in a<div>
with<div>
tags, as above.The outer
<div>
container receives theid
attribute of the widget,if defined, orBoundField.auto_id
otherwise.When looping over the radio buttons, the
label
andinput
tags includefor
andid
attributes, respectively. Each radio button has anid_for_label
attribute to output the element’s ID.
CheckboxSelectMultiple
¶
- class
CheckboxSelectMultiple
¶ template_name
:'django/forms/widgets/checkbox_select.html'
option_template_name
:'django/forms/widgets/checkbox_option.html'
Similar to
SelectMultiple
, but rendered as a list of checkboxes:<div><div><inputtype="checkbox"name="..."></div> ...</div>
The outer
<div>
container receives theid
attribute of the widget,if defined, orBoundField.auto_id
otherwise.
LikeRadioSelect
, you can loop over the individual checkboxes for thewidget’s choices. UnlikeRadioSelect
, the checkboxes won’t include therequired
HTML attribute if the field is required because browser validationwould require all checkboxes to be checked instead of at least one.
When looping over the checkboxes, thelabel
andinput
tags includefor
andid
attributes, respectively. Each checkbox has anid_for_label
attribute to output the element’s ID.
File upload widgets¶
Composite widgets¶
MultipleHiddenInput
¶
- class
MultipleHiddenInput
¶ template_name
:'django/forms/widgets/multiple_hidden.html'
- Renders as: multiple
<inputtype="hidden"...>
tags
A widget that handles multiple hidden widgets for fields that have a listof values.
SplitDateTimeWidget
¶
- class
SplitDateTimeWidget
¶ template_name
:'django/forms/widgets/splitdatetime.html'
Wrapper (using
MultiWidget
) around two widgets:DateInput
for the date, andTimeInput
for the time. Must be used withSplitDateTimeField
rather thanDateTimeField
.SplitDateTimeWidget
has several optional arguments:date_format
¶Similar to
DateInput.format
time_format
¶Similar to
TimeInput.format
date_attrs
¶
time_attrs
¶Similar to
Widget.attrs
. A dictionary containing HTMLattributes to be set on the renderedDateInput
andTimeInput
widgets, respectively. If these attributes aren’tset,Widget.attrs
is used instead.
SplitHiddenDateTimeWidget
¶
- class
SplitHiddenDateTimeWidget
¶ template_name
:'django/forms/widgets/splithiddendatetime.html'
Similar to
SplitDateTimeWidget
, but usesHiddenInput
forboth date and time.
SelectDateWidget
¶
- class
SelectDateWidget
¶ template_name
:'django/forms/widgets/select_date.html'
Wrapper around three
Select
widgets: one each formonth, day, and year.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
¶An optional dict of months to use in the “months” select box.
The keys of the dict correspond to the month number (1-indexed) andthe 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
¶If the
DateField
is not required,SelectDateWidget
will have an empty choice at the top of thelist (which is---
by default). You can change the text of thislabel with theempty_label
attribute.empty_label
can be astring
,list
, ortuple
. When a string is used, all selectboxes will each have an empty choice with this label. Ifempty_label
is alist
ortuple
of 3 string elements, the select boxes willhave their own custom label. The labels should be in this order('year_label','month_label','day_label')
.# A custom empty label with stringfield1=forms.DateField(widget=SelectDateWidget(empty_label="Nothing"))# A custom empty label with tuplefield1=forms.DateField(widget=SelectDateWidget(empty_label=("Choose Year","Choose Month","Choose Day"),),)