小部件

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<!DOCTYPE html>. For example, it uses boolean attributes such as checkedrather than the XHTML style of checked='checked'.

小技巧

Widgets should not be confused with the form 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 be assigned 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 the widget argument on the field definition. Forexample:

  1. from django import forms
  2.  
  3. class CommentForm(forms.Form):
  4. name = forms.CharField()
  5. url = forms.URLField()
  6. comment = forms.CharField(widget=forms.Textarea)

This would specify a form with a comment that uses a larger Textareawidget, rather than the default TextInput 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:

  1. from django import forms
  2.  
  3. BIRTH_YEAR_CHOICES = ['1980', '1981', '1982']
  4. FAVORITE_COLORS_CHOICES = [
  5. ('blue', 'Blue'),
  6. ('green', 'Green'),
  7. ('black', 'Black'),
  8. ]
  9.  
  10. class SimpleForm(forms.Form):
  11. birth_year = forms.DateField(widget=forms.SelectDateWidget(years=BIRTH_YEAR_CHOICES))
  12. favorite_colors = forms.MultipleChoiceField(
  13. required=False,
  14. widget=forms.CheckboxSelectMultiple,
  15. choices=FAVORITE_COLORS_CHOICES,
  16. )

See the Built-in widgets for more information about which widgetsare available and which arguments they accept.

Widgets inheriting from the Select widget

Widgets inheriting from the Select widget deal with choices. Theypresent the user with a list of options to choose from. The different widgetspresent this choice differently; the Select widget itself uses a<select> HTML list representation, while RadioSelect uses radiobuttons.

Select widgets are used by default on ChoiceField fields. Thechoices displayed on the widget are inherited from the ChoiceField andchanging ChoiceField.choices will update Select.choices. Forexample:

  1. >>> from django import forms
  2. >>> CHOICES = [('1', 'First'), ('2', 'Second')]
  3. >>> choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
  4. >>> choice_field.choices
  5. [('1', 'First'), ('2', 'Second')]
  6. >>> choice_field.widget.choices
  7. [('1', 'First'), ('2', 'Second')]
  8. >>> choice_field.widget.choices = []
  9. >>> choice_field.choices = [('1', 'First and only')]
  10. >>> choice_field.widget.choices
  11. [('1', 'First and only')]

Widgets which offer a choices attribute can however be usedwith fields which are not based on choice — such as a CharField —but it is recommended to use a ChoiceField-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 all TextInput widgets will appear the sameon 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 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:

  1. from django import forms
  2.  
  3. class CommentForm(forms.Form):
  4. name = forms.CharField()
  5. url = forms.URLField()
  6. comment = forms.CharField()

This form will include three default TextInput widgets, with defaultrendering — no CSS class, no extra attributes. This means that the input boxesprovided for each widget will be rendered exactly the same:

  1. >>> f = CommentForm(auto_id=False)
  2. >>> f.as_table()
  3. <tr><th>Name:</th><td><input type="text" name="name" required></td></tr>
  4. <tr><th>Url:</th><td><input type="url" name="url" required></td></tr>
  5. <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 the Widget.attrs argument when creating the widget:

  1. class CommentForm(forms.Form):
  2. name = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))
  3. url = forms.URLField()
  4. comment = forms.CharField(widget=forms.TextInput(attrs={'size': '40'}))

You can also modify a widget in the form definition:

  1. class CommentForm(forms.Form):
  2. name = forms.CharField()
  3. url = forms.URLField()
  4. comment = forms.CharField()
  5.  
  6. name.widget.attrs.update({'class': 'special'})
  7. 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 the Form.fields attribute:

  1. class CommentForm(forms.ModelForm):
  2. def __init__(self, *args, **kwargs):
  3. super().__init__(*args, **kwargs)
  4. self.fields['name'].widget.attrs.update({'class': 'special'})
  5. self.fields['comment'].widget.attrs.update(size='40')

Django will then include the extra attributes in the rendered output:

  1. >>> f = CommentForm(auto_id=False)
  2. >>> f.as_table()
  3. <tr><th>Name:</th><td><input type="text" name="name" class="special" required></td></tr>
  4. <tr><th>Url:</th><td><input type="url" name="url" required></td></tr>
  5. <tr><th>Comment:</th><td><input type="text" name="comment" size="40" required></td></tr>

You can also set the HTML id using attrs. SeeBoundField.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 eitherdefine a "Media" inner class orcreate a "media" property.

These methods involve somewhat advanced Python programming and are described indetail in the Form Assets topic guide.

Base widget classes

Base widget classes Widget and MultiWidget are subclassed byall the built-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 attributeattrs. You may also implement or override therender() method on custom widgets.

    • attrs
    • A dictionary containing HTML attributes to be set on the renderedwidget.
  1. >>> from django import forms
  2. >>> name = forms.TextInput(attrs={'size': 10, 'title': 'Your name'})
  3. >>> name.render('name', 'A name')
  4. '<input title="Your name" type="text" name="name" value="A name" size="10">'

If you assign a value of True or False to an attribute,it will be rendered as an HTML5 boolean attribute:

  1. >>> name = forms.TextInput(attrs={'required': True})
  2. >>> name.render('name', 'A name')
  3. '<input name="name" type="text" value="A name" required>'
  4. >>>
  5. >>> name = forms.TextInput(attrs={'required': False})
  6. >>> name.render('name', 'A name')
  7. '<input name="name" type="text" value="A name">'
  • supports_microseconds
  • An attribute that defaults to True. If set to False, themicroseconds part of datetime andtime values will be set to 0.

  • formatvalue(_value)[源代码]

  • Cleans and returns a value for use in the widget template. valueisn't guaranteed to be valid input, therefore subclass implementationsshould program defensively.

  • getcontext(_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 the name 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 by format_value().
    • 'attrs': HTML attributes to be set on the rendered widget. Thecombination of the attrs attribute and the attrs argument.
    • 'template_name': The value of self.template_name.Widget subclasses can provide custom context values by overridingthis method.
  • idforlabel(_id)[源代码]

  • Returns the HTML ID attribute of this widget for use by a <label>,given the ID of the field. Returns None if 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, renderer=None)[源代码]
  • Renders a widget to HTML using the given renderer. If renderer isNone, the renderer from the FORM_RENDERER setting isused.

  • valuefrom_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. Returns Noneif a value wasn't provided. Note also that value_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.

  • valueomitted_from_data(_data, files, name)[源代码]

  • Given data and files 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<select multiple> don't appear in the data of an HTML formsubmission, so it's unknown whether or not the user submitted a value.

  • userequired_attribute(_initial)[源代码]
  • Given a form field's initial value, returns whether or not thewidget can be rendered with the required HTML attribute. Forms usethis method along with Field.required and Form.use_required_attribute to determine whether or notto display the required attribute for each field.

By default, returns False for hidden widgets and Trueotherwise. Special cases are ClearableFileInput,which returns False when initial is not set, andCheckboxSelectMultiple, which always returnsFalse because 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 textarea element may want to always return False toavoid browser validation on the hidden field.

MultiWidget

MultiWidget has one required argument:

  • widgets
  • An iterable containing the widgets needed.

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 method must 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:

  1. from django.forms import MultiWidget
  2.  
  3. class SplitDateTimeWidget(MultiWidget):
  4.  
  5. # ...
  6.  
  7. def decompress(self, value):
  8. if value:
  9. return [value.date(), value.time()]
  10. return [None, None]

小技巧

Note that MultiValueField has acomplementary method compress()with the opposite responsibility - to combine cleaned values ofall member fields into one.

It provides some custom context:

  • getcontext(_name, value, attrs)[源代码]
  • In addition to the 'widget' key described inWidget.get_context(), MultiValueWidget adds awidget['subwidgets'] key.

These can be looped over in the widget template:

  1. {% for subwidget in widget.subwidgets %}
  2. {% include subwidget.template_name with widget=subwidget %}
  3. {% 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 a DateField rather thana MultiValueField, thus we have implementedvalue_from_datadict():

  1. from datetime import date
  2. from django.forms import widgets
  3.  
  4. class DateSelectorWidget(widgets.MultiWidget):
  5. def __init__(self, attrs=None):
  6. # create choices for days, months, years
  7. # example below, the rest snipped for brevity.
  8. years = [(year, year) for year in (2011, 2012, 2013)]
  9. _widgets = (
  10. widgets.Select(attrs=attrs, choices=days),
  11. widgets.Select(attrs=attrs, choices=months),
  12. widgets.Select(attrs=attrs, choices=years),
  13. )
  14. super().__init__(_widgets, attrs)
  15.  
  16. def decompress(self, value):
  17. if value:
  18. return [value.day, value.month, value.year]
  19. return [None, None, None]
  20.  
  21. def value_from_datadict(self, data, files, name):
  22. datelist = [
  23. widget.value_from_datadict(data, files, name + '_%s' % i)
  24. for i, widget in enumerate(self.widgets)]
  25. try:
  26. D = date(
  27. day=int(datelist[0]),
  28. month=int(datelist[1]),
  29. year=int(datelist[2]),
  30. )
  31. except ValueError:
  32. return ''
  33. else:
  34. return str(D)

The constructor creates several Select widgets in a tuple. Thesuper class uses this tuple to setup the widget.

The required method decompress() breaks up adatetime.date value into the day, month, and year values correspondingto each widget. Note how the method handles the case where value isNone.

The default implementation of value_from_datadict() returnsa list of values corresponding to each Widget. This is appropriatewhen using a MultiWidget with a MultiValueField,but since we want to use this widget with a DateFieldwhich takes a single value, we have overridden this method to combine thedata of all the subwidgets into a datetime.date. The method extractsdata from the POST dictionary and constructs and validates the date.If it is valid, we return the string, otherwise, we return an empty stringwhich will cause form.is_valid to return False.

Built-in widgets

Django provides a representation of all the basic HTML widgets, plus somecommonly used groups of widgets in the django.forms.widgets module,including the input of text, various checkboxesand 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.

TextInput

  • class TextInput[源代码]
    • input_type: 'text'
    • template_name: 'django/forms/widgets/text.html'
    • Renders as: <input type="text" …>

NumberInput

  • class NumberInput[源代码]
    • input_type: 'number'
    • template_name: 'django/forms/widgets/number.html'
    • Renders as: <input type="number" …>Beware that not all browsers support entering localized numbers innumber input types. Django itself avoids using them for fields havingtheir localize property set to True.

EmailInput

  • class EmailInput[源代码]
    • input_type: 'email'
    • template_name: 'django/forms/widgets/email.html'
    • Renders as: <input type="email" …>

URLInput

  • class URLInput[源代码]
    • input_type: 'url'
    • template_name: 'django/forms/widgets/url.html'
    • Renders as: <input type="url" …>

PasswordInput

  • class PasswordInput[源代码]
    • input_type: 'password'
    • template_name: 'django/forms/widgets/password.html'
    • Renders as: <input type="password" …>Takes one optional argument:

    • render_value

    • Determines whether the widget will have a value filled in when theform is re-displayed after a validation error (default is False).

HiddenInput

  • class HiddenInput[源代码]
    • input_type: 'hidden'
    • template_name: 'django/forms/widgets/hidden.html'
    • Renders as: <input type="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: <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 firstformat found in DATE_INPUT_FORMATS and respectsFormat localization.

DateTimeInput

  • class DateTimeInput[源代码]
    • input_type: 'text'
    • template_name: 'django/forms/widgets/datetime.html'
    • Renders as: <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 firstformat found in DATETIME_INPUT_FORMATS and 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_microseconds attribute set to True.

TimeInput

  • class TimeInput[源代码]
    • input_type: 'text'
    • template_name: 'django/forms/widgets/time.html'
    • Renders as: <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 firstformat found in TIME_INPUT_FORMATS and respectsFormat localization.

For the treatment of microseconds, see DateTimeInput.

Textarea

  • class Textarea[源代码]
    • template_name: 'django/forms/widgets/textarea.html'
    • Renders as: <textarea>…</textarea>

Selector and checkbox widgets

These widgets make use of the HTML elements <select>,<input type="checkbox">, and <input type="radio">.

Widgets that render multiple choices have an option_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

  • class CheckboxInput[源代码]
    • input_type: 'checkbox'
    • template_name: 'django/forms/widgets/checkbox.html'
    • Renders as: <input type="checkbox" …>Takes one optional argument:

    • check_test

    • A callable that takes the value of the CheckboxInput and returnsTrue if the checkbox should be checked for that value.

Select

  • class Select[源代码]
    • template_name: 'django/forms/widgets/select.html'
    • option_template_name: 'django/forms/widgets/select_option.html'
    • Renders as: <select><option …>…</select>
    • choices
    • This attribute is optional when the form field does not have achoices attribute. If it does, it will override anything you sethere when the attribute is updated on the Field.

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

  • class SelectMultiple[源代码]
    • template_name: 'django/forms/widgets/select.html'
    • option_template_name: 'django/forms/widgets/select_option.html'Similar to Select, but allows multiple selection:<select multiple>…</select>

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<li> tags:
  1. <ul>
  2. <li><input type="radio" name="..."></li>
  3. ...
  4. </ul>

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 a RadioSelect as its widget:

  1. {% for radio in myform.beatles %}
  2. <div class="myradio">
  3. {{ radio }}
  4. </div>
  5. {% endfor %}

This would generate the following HTML:

  1. <div class="myradio">
  2. <label for="id_beatles_0"><input id="id_beatles_0" name="beatles" type="radio" value="john" required> John</label>
  3. </div>
  4. <div class="myradio">
  5. <label for="id_beatles_1"><input id="id_beatles_1" name="beatles" type="radio" value="paul" required> Paul</label>
  6. </div>
  7. <div class="myradio">
  8. <label for="id_beatles_2"><input id="id_beatles_2" name="beatles" type="radio" value="george" required> George</label>
  9. </div>
  10. <div class="myradio">
  11. <label for="id_beatles_3"><input id="id_beatles_3" name="beatles" type="radio" value="ringo" required> Ringo</label>
  12. </div>

That included the <label> tags. To get more granular, you can use eachradio button's tag, choice_label and id_for_label attributes.For example, this template…

  1. {% for radio in myform.beatles %}
  2. <label for="{{ radio.id_for_label }}">
  3. {{ radio.choice_label }}
  4. <span class="radio">{{ radio.tag }}</span>
  5. </label>
  6. {% endfor %}

…will result in the following HTML:

  1. <label for="id_beatles_0">
  2. John
  3. <span class="radio"><input id="id_beatles_0" name="beatles" type="radio" value="john" required></span>
  4. </label>
  5.  
  6. <label for="id_beatles_1">
  7. Paul
  8. <span class="radio"><input id="id_beatles_1" name="beatles" type="radio" value="paul" required></span>
  9. </label>
  10.  
  11. <label for="id_beatles_2">
  12. George
  13. <span class="radio"><input id="id_beatles_2" name="beatles" type="radio" value="george" required></span>
  14. </label>
  15.  
  16. <label for="id_beatles_3">
  17. Ringo
  18. <span class="radio"><input id="id_beatles_3" name="beatles" type="radio" value="ringo" required></span>
  19. </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 the id attribute of the widget,if defined, or BoundField.auto_id otherwise.

When looping over the radio buttons, the label and input tags includefor and id 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:
  1. <ul>
  2. <li><input type="checkbox" name="..." ></li>
  3. ...
  4. </ul>

The outer <ul> container receives the id attribute of the widget,if defined, or BoundField.auto_id otherwise.

Like RadioSelect, you can loop over the individual checkboxes for thewidget's choices. Unlike RadioSelect, 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, the label and input tags includefor and id attributes, respectively. Each checkbox has anid_for_label attribute to output the element's ID.

File upload widgets

FileInput

  • class FileInput[源代码]
    • template_name: 'django/forms/widgets/file.html'
    • Renders as: <input type="file" …>

ClearableFileInput

  • class ClearableFileInput[源代码]
    • template_name: 'django/forms/widgets/clearable_file_input.html'
    • Renders as: <input type="file" …> with an additional checkboxinput to clear the field's value, if the field is not required and hasinitial data.

Composite widgets

MultipleHiddenInput

  • class MultipleHiddenInput[源代码]
    • template_name: 'django/forms/widgets/multiple_hidden.html'
    • Renders as: multiple <input type="hidden" …> tagsA widget that handles multiple hidden widgets for fields that have a listof values.

    • choices

    • This attribute is optional when the form field does not have achoices attribute. If it does, it will override anything you sethere when the attribute is updated on the Field.

SplitDateTimeWidget

SplitDateTimeWidget has several optional arguments:

SplitHiddenDateTimeWidget

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:

  1. MONTHS = {
  2. 1:_('jan'), 2:_('feb'), 3:_('mar'), 4:_('apr'),
  3. 5:_('may'), 6:_('jun'), 7:_('jul'), 8:_('aug'),
  4. 9:_('sep'), 10:_('oct'), 11:_('nov'), 12:_('dec')
  5. }
  • 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 the empty_label attribute. empty_label can be astring, list, or tuple. When a string is used, all selectboxes will each have an empty choice with this label. If empty_labelis a list or tuple 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').
  1. # A custom empty label with string
  2. field1 = forms.DateField(widget=SelectDateWidget(empty_label="Nothing"))
  3.  
  4. # A custom empty label with tuple
  5. field1 = forms.DateField(
  6. widget=SelectDateWidget(
  7. empty_label=("Choose Year", "Choose Month", "Choose Day"),
  8. ),
  9. )