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.
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 canjust use thewidget argument on the field definition. Forexample:
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 largerTextareawidget, 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 simple 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)>>>f.as_table()<tr><th>Name:</th><td><input type="text" name="name" required /></td></tr><tr><th>Url:</th><td><input type="url" name="url" required /></td></tr><tr><th>Comment:</th><td><input type="text" name="comment" required /></td></tr>
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'}))
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" required /></td></tr><tr><th>Url:</th><td><input type="url" name="url" required /></td></tr><tr><th>Comment:</th><td><input type="text" name="comment" size="40" required /></td></tr>
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)[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 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" required />'
If you assign a value of
TrueorFalseto 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 ofdatetimeandtimevalues will be set to0.New in Django 1.9:In older versions, this attribute was only defined on the dateand time widgets (as
False).
format_value(value)¶Cleans and returns a value for use in the widget template.
valueisn’t guaranteed to be valid input, therefore subclass implementationsshould program defensively.Changed in Django 1.10:In older versions, this method is a private API named
_format_value(). The old name will work until Django 2.0.
id_for_label(self,id_)[source]¶Returns the HTML ID attribute of this widget for use by a
<label>,given the ID of the field. ReturnsNoneif an ID isn’t available.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)[source]¶Returns HTML for the widget, as a Unicode string. This method must beimplemented by the subclass, otherwise
NotImplementedErrorwill beraised.The ‘value’ given is not guaranteed to be valid input, thereforesubclass implementations should program defensively.
value_from_datadict(data,files,name)[source]¶Given a dictionary of data and this widget’s name, returns the valueof this widget.
filesmay contain data coming fromrequest.FILES. ReturnsNoneif a value wasn’t provided. Note also thatvalue_from_datadictmaybe 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)[source]¶- New in Django 1.10.2.
Given
dataandfilesdictionaries 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 returnFalsebecause 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_required_attribute(initial)[source]¶- New in Django 1.10.1.
Given a form field’s
initialvalue, returns whether or not thewidget can be rendered with therequiredHTML attribute. Forms usethis method along withField.requiredandForm.use_required_attributeto determine whether or notto display therequiredattribute for each field.By default, returns
Falsefor hidden widgets andTrueotherwise. Special cases areClearableFileInput,which returnsFalsewheninitialis not set, andCheckboxSelectMultiple, which always returnsFalsebecause browser validation would require all checkboxes to bechecked 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
textareaelement may want to always returnFalsetoavoid browser validation on the hidden field.
MultiWidget¶
- class
MultiWidget(widgets,attrs=None)[source]¶ A widget that is composed of multiple widgets.
MultiWidgetworks hand in hand with theMultiValueField.MultiWidgethas 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 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
SplitDateTimeWidgetturns adatetimevalue into a list with date and time splitinto two separate values:fromdjango.formsimportMultiWidgetclassSplitDateTimeWidget(MultiWidget):# ...defdecompress(self,value):ifvalue:return[value.date(),value.time().replace(microsecond=0)]return[None,None]
Tip
Note that
MultiValueFieldhas acomplementary methodcompress()with the opposite responsibility - to combine cleaned values ofall member fields into one.
Other methods that may be useful to override include:
render(name,value,attrs=None)[source]¶Argument
valueis handled differently in this method from thesubclasses ofWidgetbecause it has to figure out how tosplit a single value for display in multiple widgets.The
valueargument used when rendering can be one of two things:- A
list. - A single value (e.g., a string) that is the “compressed” representationof a
listof values.
If
valueis a list, the output ofrender()willbe a concatenation of rendered child widgets. Ifvalueis not alist, 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 listis rendered with the corresponding widget – the first value isrendered in the first widget, the second value is rendered in thesecond 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 stringrepresenting the HTML for the whole lot.
This hook allows you to format the HTML design of the widgets any wayyou’d like.
Here’s an example widget which subclasses
MultiWidgetto displaya date with the day, month, and year in different select boxes. This widgetis intended to be used with aDateFieldrather thanaMultiValueField, thus we have implementedvalue_from_datadict():fromdatetimeimportdatefromdjango.formsimportwidgetsclassDateSelectorWidget(widgets.MultiWidget):def__init__(self,attrs=None):# create choices for days, months, years# example below, the rest snipped for brevity.years=[(year,year)foryearin(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)defdecompress(self,value):ifvalue:return[value.day,value.month,value.year]return[None,None,None]defformat_output(self,rendered_widgets):return''.join(rendered_widgets)defvalue_from_datadict(self,data,files,name):datelist=[widget.value_from_datadict(data,files,name+'_%s'%i)fori,widgetinenumerate(self.widgets)]try:D=date(day=int(datelist[0]),month=int(datelist[1]),year=int(datelist[2]),)exceptValueError:return''else:returnstr(D)
The constructor creates several
Selectwidgets in a tuple. Thesuperclass uses this tuple to setup the widget.The
format_output()method is fairly vanilla here (infact, it’s the same as what’s been implemented as the default forMultiWidget), but the idea is that you could add custom HTML betweenthe widgets should you wish.The required method
decompress()breaks up adatetime.datevalue into the day, month, and year values correspondingto each widget. Note how the method handles the case wherevalueisNone.The default implementation of
value_from_datadict()returnsa list of values corresponding to eachWidget. This is appropriatewhen using aMultiWidgetwith aMultiValueField,but since we want to use this widget with aDateFieldwhich takes a single value, we have overridden this method to combine thedata of all the subwidgets into adatetime.date. The method extractsdata from thePOSTdictionary and constructs and validates the date.If it is valid, we return the string, otherwise, we return an empty stringwhich will causeform.is_validto returnFalse.
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.
NumberInput¶
PasswordInput¶
HiddenInput¶
- class
HiddenInput[source]¶ Hidden input:
<inputtype='hidden'...>Note that there also is a
MultipleHiddenInputwidget thatencapsulates a set of hidden input elements.
DateInput¶
- class
DateInput[source]¶ Date input as a simple text box:
<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
formatargument is provided, the default format is the firstformat found inDATE_INPUT_FORMATSand respectsFormat localization.
DateTimeInput¶
- class
DateTimeInput[source]¶ Date/time input as a simple text box:
<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
formatargument is provided, the default format is the firstformat found inDATETIME_INPUT_FORMATSand respectsFormat localization.By default, the microseconds part of the time value is always set to
0.If microseconds are required, use a subclass with thesupports_microsecondsattribute set toTrue.
TimeInput¶
- class
TimeInput[source]¶ Time input as a simple text box:
<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
formatargument is provided, the default format is the firstformat found inTIME_INPUT_FORMATSand respectsFormat localization.For the treatment of microseconds, see
DateTimeInput.
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><inputtype='radio'name='...'></li> ...</ul>
For more granular control over the generated markup, you can loop over theradio buttons in the template. Assuming a form
myformwith a fieldbeatlesthat uses aRadioSelectas its widget:{%forradioinmyform.beatles%}<divclass="myradio">{{radio}}</div>{%endfor%}
This would generate the following HTML:
<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>
That included the
<label>tags. To get more granular, you can use eachradio button’stag,choice_labelandid_for_labelattributes.For example, this template…{%forradioinmyform.beatles%}<labelfor="{{radio.id_for_label}}">{{radio.choice_label}}<spanclass="radio">{{radio.tag}}</span></label>{%endfor%}
…will result in the following HTML:
<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>
If you decide not to loop over the radio buttons – e.g., if your templatesimply includes
{{myform.beatles}}– they’ll be output in a<ul>with<li>tags, as above.The outer
<ul>container receives theidattribute of the widget,if defined, orBoundField.auto_idotherwise.When looping over the radio buttons, the
labelandinputtags includeforandidattributes, respectively. Each radio button has anid_for_labelattribute to output the element’s ID.
CheckboxSelectMultiple¶
- class
CheckboxSelectMultiple[source]¶ Similar to
SelectMultiple, but rendered as a list of checkbuttons:<ul><li><inputtype='checkbox'name='...'></li> ...</ul>
The outer
<ul>container receives theidattribute of the widget,if defined, orBoundField.auto_idotherwise.
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¶
SplitDateTimeWidget¶
- class
SplitDateTimeWidget[source]¶ Wrapper (using
MultiWidget) around two widgets:DateInputfor the date, andTimeInputfor the time. Must be used withSplitDateTimeFieldrather thanDateTimeField.SplitDateTimeWidgethas two optional attributes:date_format¶Similar to
DateInput.format
time_format¶Similar to
TimeInput.format
SplitHiddenDateTimeWidget¶
- class
SplitHiddenDateTimeWidget[source]¶ Similar to
SplitDateTimeWidget, but usesHiddenInputforboth date and time.
SelectDateWidget¶
- class
SelectDateWidget[source]¶ Wrapper around three
Selectwidgets: 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
DateFieldis not required,SelectDateWidgetwill have an empty choice at the top of thelist (which is---by default). You can change the text of thislabel with theempty_labelattribute.empty_labelcan be astring,list, ortuple. When a string is used, all selectboxes will each have an empty choice with this label. Ifempty_labelis alistortupleof 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"),),)
Changed in Django 1.9:This widget used to be located in the
django.forms.extras.widgetspackage. It is now defined indjango.forms.widgetsand like theother widgets it can be imported directly fromdjango.forms.

