WidgetLink to this heading

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.

The HTML generated by the built-in widgets uses HTML5 syntax, targeting <!DOCTYPE html>. For example, it uses boolean attributes such as checked rather than the XHTML style of checked='checked'.

Menentukan widgetLink to this heading

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 KelaS-kelas Field siap-pakai.

Bagaimanapun, jika anda ingin menggunakan widget berbeda untuk bidang, anda cukup menggunakan argumen widget pada pengertian bidang. Sebagai contoh:

Code
from django import forms

class CommentForm(forms.Form):
    name = forms.CharField()
    url = forms.URLField()
    comment = forms.CharField(widget=forms.Textarea)

Ini akan menentukan formulir dengan komentar yang menggunakan widget Textarea terbesar, daripada widget TextInput awal.

Mengatur argumen untuk widgetLink to this heading

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:

Code
from django import forms

BIRTH_YEAR_CHOICES = ['1980', '1981', '1982']
FAVORITE_COLORS_CHOICES = [
    ('blue', 'Blue'),
    ('green', 'Green'),
    ('black', 'Black'),
]

class SimpleForm(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,
    )

Lihat Widget pasang tetap untuk informasi lebih tentang widget-widget mana tersedia dan argumen mana mereka terima.

Widget warisan dari widget SelectLink to this heading

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.

Widget Select digunakan secara awalan pada ChoiceField fields. Pilihan-pilihan ditampilkan pada widget diwariskan dari ChoiceField dan merubah ChoiceField.choices akan memperbaharui Select.choices. Sebagai contoh:

Code
>>> 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.

Menyesuaikan instance widgetLink to this heading

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.

Ada dua cara menyesuaikan widget: per widget instance dan per widget class.

Menggayakan instance widgetLink to this heading

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).

Sebagai contoh, ambil formulir sederhana berikut:

Code
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:

Code
>>> 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. 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:

Code
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'}))

Anda dapat juga merubah widget dalam pengertian formulir:

Code
class CommentForm(forms.Form):
    name = forms.CharField()
    url = forms.URLField()
    comment = forms.CharField()

    name.widget.attrs.update({'class': 'special'})
    comment.widget.attrs.update(size='40')

Atau jika bidang tidak dinyatakan langsung pada formulir (seperti bidang formulir model), anda dapat menggunakan atribut Form.fields:

Code
class CommentForm(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 kemudian akan menyertakan atribut tambahan dalam keluaran dibangun:

Code
>>> 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>

Anda dapat juga mensetel id HTML menggunakan attrs. Lihat BoundField.id_for_label sebagai contoh.

Menggayakan kelas widgetLink to this heading

Dengan widget, itu memungkinkan menambahkan assets (css dan javascript) dan lebih mendalam menyesuaikan penampilan dan perilaku mereka.

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.

Kelas-kelas widget dasarLink to this heading

Base widget classes Widget and MultiWidget are subclassed by all the built-in widgets and may serve as a foundation for custom widgets.

WidgetLink to this heading

class Widget(attrs=None)Link to this definition

This abstract class cannot be rendered, but provides the basic attribute attrs. You may also implement or override the render() method on custom widgets.

attrsLink to this definition

Sebuah dictionary mengandung atribut HTML untuk disetel pada widget dibangun.

Python console
>>> 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">'

Jika anda memberikan sebuah nilai dari True atau False ke sebuah atribut, itu akan dibangun sebagai sebuah atribut boolean HTML5:

Code
>>> 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_microsecondsLink to this definition

Sebuah atribut yang awalan menjadi True. Jika disetel menjadi False, mikrodetik bagian dari nilai-nilai datetime dan time akan disetel menjadi 0.

format_value(value)Link to this definition

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

get_context(name, value, attrs)Link to this definition

Returns a dictionary of values to use when rendering the widget template. By default, the dictionary contains a single key, 'widget', which is a dictionary representation of the widget containing the following keys:

  • 'name': Nama dari bidang dari argumen name.

  • 'is_hidden': Sebuah boolean menunjukkan apakah atau tidak widget ini tersembunyi.

  • 'required': Sebuah boolean menunjukkan apakah atau tidak bidang untuk widget ini diwajibkan.

  • 'value': Nilai seperti dikembalikan oleh format_value().

  • 'attrs': Atribut-atribut HTML untuk disetel pada widget dibangun. Perpaduan dari atribut attrs dan argumen attrs.

  • 'template_name': Nilai dari self.template_name.

Subkelas-subkelas Widget dapat menyediakan penyesuaian nilai konteks dengan menimpa metode ini.

id_for_label(id_)Link to this definition

Mengebalikan atribut ID HTML dari widget ini untuk digunakan oleh sebuah <label>, diberikan ID dari bidang. Mengembalikan None jika sebuah ID tidak tersedia.

This hook is necessary because some widgets have multiple HTML elements and, thus, multiple IDs. In that case, this method should return an ID value that corresponds to the first ID in the widget's tags.

render(name, value, attrs=None, renderer=None)Link to this definition

Renders a widget to HTML using the given renderer. If renderer is None, the renderer from the FORM_RENDERER setting is used.

value_from_datadict(data, files, name)Link to this definition

Given a dictionary of data and this widget's name, returns the value of this widget. files may contain data coming from request.FILES. Returns None if a value wasn't provided. Note also that value_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.

value_omitted_from_data(data, files, name)Link to this definition

Given data and files dictionaries and this widget's name, returns whether or not there's data or files for the widget.

Hasil metode mempengaruhi apakah atau tidak sebuah bidang di sebuah model formulir falls back to its default.

Special cases are CheckboxInput, CheckboxSelectMultiple, and SelectMultiple, which always return False because an unchecked checkbox and unselected <select multiple> don't appear in the data of an HTML form submission, so it's unknown whether or not the user submitted a value.

use_required_attribute(initial)Link to this definition

Given a form field's initial value, returns whether or not the widget can be rendered with the required HTML attribute. Forms use this method along with Field.required and Form.use_required_attribute to determine whether or not to display the required attribute for each field.

By default, returns False for hidden widgets and True otherwise. Special cases are ClearableFileInput, which returns False when initial is not set, and CheckboxSelectMultiple, which always returns False because browser validation would require all checkboxes to be checked instead of at least one.

Override this method in custom widgets that aren't compatible with browser validation. For example, a WSYSIWG text editor widget backed by a hidden textarea element may want to always return False to avoid browser validation on the hidden field.

MultiWidgetLink to this heading

class MultiWidget(widgets, attrs=None)Link to this definition

A widget that is composed of multiple widgets. MultiWidget works hand in hand with the MultiValueField.

MultiWidget mempunyai satu argumen diwajibkan:

widgetsLink to this definition

Sebuah perulangan mengandung widget dibutuhkan.

Dan satu cara diwajibkan:

decompress(value)Link to this definition

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 a datetime value into a list with date and time split into two separate values:

Code
from django.forms import MultiWidget

class SplitDateTimeWidget(MultiWidget):

    # ...

    def decompress(self, value):
        if value:
            return [value.date(), value.time()]
        return [None, None]

Itu menyediakan beberapa konteks penyesuaian:

get_context(name, value, attrs)Link to this definition

Sebagai tambahan pada kunci 'widget' digambarkan dalam Widget.get_context(), MultiValueWidget menambahkan kunci widget['subwidgets'].

Ini dapat dilingkarkan dalam cetakan widget:

Django template
{% for subwidget in widget.subwidgets %}
    {% include subwidget.template_name with widget=subwidget %}
{% endfor %}

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 a DateField rather than a MultiValueField, thus we have implemented value_from_datadict():

Code
from datetime import date
from django import forms

class DateSelectorWidget(forms.MultiWidget):
    def __init__(self, attrs=None):
        days = [(day, day) for day in range(1, 32)]
        months = [(month, month) for month in range(1, 13)]
        years = [(year, year) for year in [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)

    def decompress(self, value):
        if isinstance(value, date):
            return [value.day, value.month, value.year]
        elif isinstance(value, str):
            year, month, day = value.split('-')
            return [day, month, year]
        return [None, None, None]

    def value_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. The super() method uses this list to setup the widget.

The required method decompress() breaks up a datetime.date value into the day, month, and year values corresponding to each widget. If an invalid date was selected, such as the non-existent 30th February, the DateField passes this method a string instead, so that needs parsing. The final return handles when value is None, meaning we don't have any defaults for our subwidgets.

The default implementation of value_from_datadict() returns a list of values corresponding to each Widget. This is appropriate when using a MultiWidget with a MultiValueField. But since we want to use this widget with a DateField, which takes a single value, we have overridden this method. The implementation here combines the data from the subwidgets into a string in the format that DateField expects.

Widget pasang tetapLink to this heading

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.

Widget menangani masukan dari teksLink to this heading

Widget ini membuat penggunaan dari unsur-unsur HTML input` dan ``textarea.

TextInputLink to this heading

class TextInputLink to this definition
  • input_type: 'text'

  • template_name: 'django/forms/widgets/text.html'

  • Membangun sebagai: <input type="text" ...>

NumberInputLink to this heading

class NumberInputLink to this definition
  • input_type: 'number'

  • template_name: 'django/forms/widgets/number.html'

  • Membangun sebagai: <input type="number" ...>

Beware that not all browsers support entering localized numbers in number input types. Django itself avoids using them for fields having their localize property set to True.

EmailInputLink to this heading

class EmailInputLink to this definition
  • input_type: 'email'

  • template_name: 'django/forms/widgets/email.html'

  • Membangun sebagai: <input type="email" ...>

URLInputLink to this heading

class URLInputLink to this definition
  • input_type: 'url'

  • template_name: 'django/forms/widgets/url.html'

  • Membangun sebagai: <input type="url" ...>

PasswordInputLink to this heading

class PasswordInputLink to this definition
  • input_type: 'password'

  • template_name: 'django/forms/widgets/password.html'

  • Membangun sebagai: <input type="password" ...>

Mengambil satu argumen pilihan:

render_valueLink to this definition

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

HiddenInputLink to this heading

class HiddenInputLink to this definition
  • input_type: 'hidden'

  • template_name: 'django/forms/widgets/hidden.html'

  • Dibangun sebagai: <input type="hidden" ...>

Note that there also is a MultipleHiddenInput widget that encapsulates a set of hidden input elements.

DateInputLink to this heading

class DateInputLink to this definition
  • input_type: 'text'

  • template_name: 'django/forms/widgets/date.html'

  • Membangun sebagai: <input type="text" ...>

Mengambil argumen sama seperti TextInput, dengan satu atau lebih argumen pilihan:

formatLink to this definition

Bentuk dimana nilaiinisial bidang ini akan ditampilkan.

If no format argument is provided, the default format is the first format found in DATE_INPUT_FORMATS and respects Format localization.

DateTimeInputLink to this heading

class DateTimeInputLink to this definition
  • input_type: 'text'

  • template_name: 'django/forms/widgets/datetime.html'

  • Membangun sebagai: <input type="text" ...>

Mengambil argumen sama seperti TextInput, dengan satu atau lebih argumen pilihan:

formatLink to this definition

Bentuk dimana nilaiinisial bidang ini akan ditampilkan.

If no format argument is provided, the default format is the first format found in DATETIME_INPUT_FORMATS and respects Format localization.

By default, the microseconds part of the time value is always set to 0. If microseconds are required, use a subclass with the supports_microseconds attribute set to True.

TimeInputLink to this heading

class TimeInputLink to this definition
  • input_type: 'text'

  • template_name: 'django/forms/widgets/time.html'

  • Membangun sebagai: <input type="text" ...>

Mengambil argumen sama seperti TextInput, dengan satu atau lebih argumen pilihan:

formatLink to this definition

Bentuk dimana nilaiinisial bidang ini akan ditampilkan.

Jika tidak ada argumen format disediakan, bentuk awalan adalah bentuk pertama ditemukan dalam TIME_INPUT_FORMATS dan menghormati Format localization.

Untuk perlakuan dari mikro detik, lihat DateTimeInput.

TextareaLink to this heading

class TextareaLink to this definition
  • template_name: 'django/forms/widgets/textarea.html'

  • Membangun sebagai: <textarea>...</textarea>

Widget pemilih dan kotak centangLink to this heading

Widget ini membuat penggunaan dari unsur-unsur HTML <select>, <input type="checkbox">, dan <input type="radio">.

Widgets that render multiple choices have an option_template_name attribute that specifies the template used to render each choice. For example, for the Select widget, select_option.html renders the <option> for a <select>.

CheckboxInputLink to this heading

class CheckboxInputLink to this definition
  • input_type: 'checkbox'

  • template_name: 'django/forms/widgets/checkbox.html'

  • Membangun sebagai: <input type="checkbox" ...>

Mengambil satu argumen pilihan:

check_testLink to this definition

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

SelectLink to this heading

class SelectLink to this definition
  • template_name: 'django/forms/widgets/select.html'

  • option_template_name: 'django/forms/widgets/select_option.html'

  • Membangun sebagai: <select><option ...>...</select>

choicesLink to this definition

This attribute is optional when the form field does not have a choices attribute. If it does, it will override anything you set here when the attribute is updated on the Field.

NullBooleanSelectLink to this heading

class NullBooleanSelectLink to this definition
  • template_name: 'django/forms/widgets/select.html'

  • option_template_name: 'django/forms/widgets/select_option.html'

Pilih widget dengan pilihan 'Tidak dikenal', 'Ya' dan 'Tidak'

SelectMultipleLink to this heading

class SelectMultipleLink to this definition
  • template_name: 'django/forms/widgets/select.html'

  • option_template_name: 'django/forms/widgets/select_option.html'

Mirip pada Select, tetai mengizinkan banyak pemilihan: <select multiple>...</select>

RadioSelectLink to this heading

class RadioSelectLink to this definition
  • template_name: 'django/forms/widgets/radio.html'

  • option_template_name: 'django/forms/widgets/radio_option.html'

Mirip pada Select, tetapi dibangun sebagai daftar daritombol radio dalam <li>:

Html
<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 field beatles that uses a RadioSelect as its widget:

Django template
{% for radio in myform.beatles %}
<div class="myradio">
    {{ radio }}
</div>
{% endfor %}

Ini akan membangkitkan HTML berikut:

Html
<div class="myradio">
    <label for="id_beatles_0"><input id="id_beatles_0" name="beatles" type="radio" value="john" required> John</label>
</div>
<div class="myradio">
    <label for="id_beatles_1"><input id="id_beatles_1" name="beatles" type="radio" value="paul" required> Paul</label>
</div>
<div class="myradio">
    <label for="id_beatles_2"><input id="id_beatles_2" name="beatles" type="radio" value="george" required> George</label>
</div>
<div class="myradio">
    <label for="id_beatles_3"><input id="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 each radio button's tag, choice_label and id_for_label attributes. For example, this template...

Django template
{% for radio in myform.beatles %}
    <label for="{{ radio.id_for_label }}">
        {{ radio.choice_label }}
        <span class="radio">{{ radio.tag }}</span>
    </label>
{% endfor %}

...akan menghasilkan HTML berikut:

Html
<label for="id_beatles_0">
    John
    <span class="radio"><input id="id_beatles_0" name="beatles" type="radio" value="john" required></span>
</label>

<label for="id_beatles_1">
    Paul
    <span class="radio"><input id="id_beatles_1" name="beatles" type="radio" value="paul" required></span>
</label>

<label for="id_beatles_2">
    George
    <span class="radio"><input id="id_beatles_2" name="beatles" type="radio" value="george" required></span>
</label>

<label for="id_beatles_3">
    Ringo
    <span class="radio"><input id="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 template simply 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 include for and id attributes, respectively. Each radio button has an id_for_label attribute to output the element's ID.

CheckboxSelectMultipleLink to this heading

class CheckboxSelectMultipleLink to this definition
  • template_name: 'django/forms/widgets/checkbox_select.html'

  • option_template_name: 'django/forms/widgets/checkbox_option.html'

Mirip pada SelectMultiple, tetapi dibangun sebagai daftar dari kotak centang:

Html
<ul>
  <li><input type="checkbox" name="..." ></li>
  ...
</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 the widget's choices. Unlike RadioSelect, the checkboxes won't include the required HTML attribute if the field is required because browser validation would require all checkboxes to be checked instead of at least one.

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.

Widget unggah berkasLink to this heading

FileInputLink to this heading

class FileInputLink to this definition
  • template_name: 'django/forms/widgets/file.html'

  • Membangun sebagai: <input type="file" ...>

ClearableFileInputLink to this heading

class ClearableFileInputLink to this definition
  • template_name: 'django/forms/widgets/clearable_file_input.html'

  • Membangun sebagai: <input type="file" ...> dengan masukan kotak centang tambahan untuk membersihkan nilai bidang, jika bidang tidak diwajibkan dan mempunyai data inisial.

Widget campuranLink to this heading

MultipleHiddenInputLink to this heading

class MultipleHiddenInputLink to this definition
  • template_name: 'django/forms/widgets/multiple_hidden.html'

  • Membangun sebagai: banyak etiket <input type="hidden" ...>

A widget that handles multiple hidden widgets for fields that have a list of values.

choicesLink to this definition

This attribute is optional when the form field does not have a choices attribute. If it does, it will override anything you set here when the attribute is updated on the Field.

SplitDateTimeWidgetLink to this heading

class SplitDateTimeWidgetLink to this definition
  • template_name: 'django/forms/widgets/splitdatetime.html'

Wrapper (using MultiWidget) around two widgets: DateInput for the date, and TimeInput for the time. Must be used with SplitDateTimeField rather than DateTimeField.

SplitDateTimeWidget mempunyai beberapa argumen pilihan:

date_formatLink to this definition

Mirip ke DateInput.format

time_formatLink to this definition

Mirip ke TimeInput.format

date_attrsLink to this definition
time_attrsLink to this definition

Similar to Widget.attrs. A dictionary containing HTML attributes to be set on the rendered DateInput and TimeInput widgets, respectively. If these attributes aren't set, Widget.attrs is used instead.

SplitHiddenDateTimeWidgetLink to this heading

class SplitHiddenDateTimeWidgetLink to this definition
  • template_name: 'django/forms/widgets/splithiddendatetime.html'

Mirip pada SplitDateTimeWidget, tetapi menggunakan HiddenInput untuk kedua tanggal dan waktu.

SelectDateWidgetLink to this heading

class SelectDateWidgetLink to this definition
  • template_name: 'django/forms/widgets/select_date.html'

Pembungkus disekitar tiga widget Select: satu untuk bulan, hari dan tahun.

Mengambil beberapa argumen pilihan:

yearsLink to this definition

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.

monthsLink to this definition

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:

Code
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_labelLink to this definition

Jika DateField tidak diwajibkan, SelectDateWidget akan memiliki pilihan kosong pada atas dari daftar (yaitu --- secara awalan). Anda dapat merubah tekas dari label ini dengan atribut empty_label. empty_label dapat berupa sebuah string, list, atau tuple. Ketika sebuah string digunakan, semua kotak-kotak pilihan akan setiapnya memiliki sebuah pilihan kosong dengan label ini. Jika empty_label adalah sebuah list atau tuple dari 3 unsur string, kotak-kotak pilihan akan memiliki label penyesuaian mereka sendiri. Label harus dalam urutan ini ('year_label', 'month_label', 'day_label').

Python
# 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"),
    ),
)