ウィジェットLink to this heading

ウィジェットは、Django が HTML の input 要素の表現方法です。ウィジェットは、HTML のレンダリングをコントロールして、ウィジェットに合致する GET/POST ディクショナリからデータを取り出します。

Built-in widgets によって作られる HTML は、<!DOCTYPE html> を対象とした HTML5 シンタックスを使います。例えば、XHTML スタイルである checked='checked' よりも、checked といった boolean 属性を使います。

ウィジェットを指定するLink to this heading

フォーム上でフィールドを指定したときは、Django は描画されるデータのタイプに適したデフォルトのウィジェットを使用します。各フィールドで使われるウィジェットを調べるためには、 ビルトインの Field クラス をご覧ください。

フィールドに異なるウィジェットを使いたい場合は、フィールドを定義するときに widget 引数を使うことができます。例えば:

Code
from django import forms

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

これは、comment のフォームに対して、デフォルトの TextInput ウィジェットではなく、より大きなサイズの Textarea ウィジェットを指定しています。

ウィジェットの引数を設定するLink to this heading

多くのウィジェットは、省略可能な追加の引数を持っています; これらは、フィールド上でウィジェットを定義する際にセットできます。以下の例では、SelectDateWidget に対して years 属性がセットされます:

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

使用可能なウィジェットとそれぞれの引数の詳細については、ビルトインのウィジェット をご覧ください。

Select ウィジェットを継承したウィジェットLink to this heading

Select ウィジェットを継承したウィジェットは、選択肢を扱います。これらはユーザーに選択肢のリストを提示します。提示される選択肢はウィジェットによって異なります; Select ウィジェット自体は、<select> HTML のリスト表現を使い、一方で RadioSelect はラジオボタンを使います。

Select ウィジェットは、 ChoiceField フィールド上でデフォルトで使われます。

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')]

とは言うものの、choices 属性を提供するウィジェットは、選択肢に基づかないフィールド -- 例えば CharField -- とともに使うことができますが、選択肢がモデルに継承され、単に表示されるだけのウィジェットではないときには、ChoiceField に基づいたフィールドを使うことをお勧めします。

ウィジェットのインスタンスをカスタマイズするLink to this heading

Django は、HTML としてウィジェットをレンダリングするとき、最低限のマークアップだけをレンダリングします - Django はクラスの名前や、他のあらゆるウィジェット特有の属性を追加しません。これは、例えば、すべての TextInput ウィジェットはウェブページ上で同じに表示されることを意味します。

ウィジェットをカスタマイズする方法には 2 つあります: ウィジェットごとのインスタンスウィジェットごとのクラス です。

ウィジェットのインスタンスにスタイルを設定するLink to this heading

1 つのウィジェットのインスタンスを他と異なる見た目にしたい場合、ウィジェットのオブジェクトをインスタンス化してフォームフィールドに割り当てるタイミングで、追加の属性を指定する必要があります (そしておそらく、あなたの CSS ファイルにいくつか記述を追加する必要もあります)。

例えば、以下のサンプルフォームを見てください:

Code
from django import forms

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

このフォームは、デフォルトのレンダリングとともに、3 つのデフォルトの TextInput ウィジェットを含みます -- CSS のクラスも追加の属性もありません。これは、それぞれのウィジェットに対して提供された input ボックスが、以下とまったく同じくレンダリングされることを意味します。

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>

実際のウェブページでは、全てのウィジェットを同じ見た目にしたいことはあまりありません。コメントに対しては大きめの input 要素にしたいでしょうし、'名前' のウィジェットには特別な CSS クラスを適用したいでしょう。新しい HTML5 の input のタイプを利用するために、'type' 属性を指定することも可能です。これらを実現するためには、ウィジェットを作成するときに Widget.attrs 引数を使います:

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

You can also modify a widget in the form definition:

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

Or if the field isn't declared directly on the form (such as model form fields), you can use the Form.fields attribute:

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 はこれで、レンダリングされたアウトプットに、追加的な要素を含むようになります:

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>

attrs を使った HTML の id をセットすることもできます。BoundField.id_for_label で例をご覧ください。

ウィジェットのクラスにスタイルを設定するLink to this heading

ウィジェットとともに、アセット (cssjavascript) 、およびより詳細にカスタマイズされた見た目や動作を追加することができます。

要するに、ウィジェットをサブクラス化して、 "Media" 内部クラスの定義"media" プロパティの作成 のどちらかをする必要があります。

これらのメソッドにはやや高度なPythonプログラミングが含まれており、トピックガイド Form Assets で詳しく説明しています。

ウィジェットの base クラスLink to this heading

WidgetMultiWidget といった基本ウィジェットは、ビルトインのウィジェット によってサブクラス化され、カスタムウィジェットのための基礎となります。

ウィジェットLink to this heading

class Widget(attrs=None)Link to this definition

この抽象クラスはレンダリングできませんが、基本的な属性 render() を実行するかオーバーライドできます。

attrsLink to this definition

ディクショナリは、レンダリングされたウィジェット上にセットされる HTML の属性を含んでいます。

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

TrueFalse の値を割り当てた場合は、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

True をデフォルト値にする属性です。False にセットされた場合は、datetimetime のマイクロ秒の部分の値は、0 にセットされます。

format_value(value)Link to this definition

ウィジェットのテンプレートで使うための値を整えて返します。value は入力値が検証されるとは限りません。そのため、サブクラスの実行は防衛的にプログラムされなければなりません。

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': The name of the field from the name argument.

  • 'is_hidden': A boolean indicating whether or not this widget is hidden.

  • 'required': A boolean indicating whether or not the field for this widget is required.

  • 'value': The value as returned by format_value().

  • 'attrs': HTML attributes to be set on the rendered widget. The combination of the attrs attribute and the attrs argument.

  • 'template_name': The value of self.template_name.

Widget subclasses can provide custom context values by overriding this method.

id_for_label(id_)Link to this definition

このウィジェットのフィールドの ID が付与された <label> で使われるための HTML の ID 属性を返します。 IDが有効でない場合は None を返します。

いくつかのウィジェットは複数の HTML 要素、そして、複数の ID を持っているため、このフックが必要です。この場合、このメソッドは、ウィジェットのタグの最初の ID と一致する ID 値を返す必要があります。

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

データとこのウィジェットの名前のディクショナリが与えられ、このウィジェットの値を返します。files には request.FILES からのデータが含まれている可能性があります。値が指定されなかった場合は None を返します。 また、value_from_datadict はフォームデータの処理中に複数回呼び出される可能性があるので、カスタマイズして複雑な処理を追加する場合は、自分でキャッシュの仕組みを実装する必要があります。

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

datafiles のディクショナリとこのウィジェットの名前が与えられ、ウィジェットのためのデータやファイルが存在するかを返します。

メソッドの結果は、モデルフォームのフィールドが デフォルトに逆戻りする かどうかに影響します。

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

フォームフィールドの 初期の 値が与えられ、ウィジェットが 必要な HTML 属性とともにレンダリングできるかどうかを返します。フォームは、各フィールドに 必要な 属性を描画するかどうかを決定するために、Field.requiredForm.use_required_attribute とともにこのメソッドを使います。

デフォルトでは、hidden のウィジェットには Flase を、それ以外には True を返します。特別な場合は、initial がセットされていないとき False を返す ClearableFileInput と、ブラウザの検証が最低 1 つではなく全チェックボックスがチェックされていることを要求するため常に False を返す CheckboxSelectMultiple です。

ブラウザの検証と互換性のないカスタムウィジェットでは、このメソッドをオーバーライドしてください。例えば、ある非表示の textarea 要素が背後にある WSYSIWG テキストエディタのウィジェットは、ブラウザが非表示のフィールドを検証するのを避けるため、常に False を返したがるかもしれません。

MultiWidgetLink to this heading

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

複数のウィジェットで構成されたウィジェットです。MultiWidgetMultiValueField と協調して動作します。

MultiWidget には 1 つの必要な引数があります。

widgetsLink to this definition

必要なウィジェットを含む反復可能なものです。

それと、1 つの必要なメソッドです:

decompress(value)Link to this definition

このメソッドは、フィールドから単一の "圧縮された" 値を取り、"解凍された" 値のリストを返します。入力された値は検証済みと見なせますが、空 (empty)でないとは限りません。

このメソッドは、サブクラスによって 実行される必要があり、値が空 (empty) かもしれないので、処理は防衛的である必要があります。

"解凍" の裏にある根本的な原理は、フォームのフィールドから各ウィジェットの値に、結合された値を "分割する" 必要があることです。

以下は、SplitDateTimeWidget が どのように SplitDateTimeWidget の値を 2 つの分割された値に日付や時刻とともにリストに入れるかの例です:

Code
from django.forms import MultiWidget

class SplitDateTimeWidget(MultiWidget):

    # ...

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

It provides some custom context:

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

In addition to the 'widget' key described in Widget.get_context(), MultiValueWidget adds a widget['subwidgets'] key.

These can be looped over in the widget template:

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

異なるセレクトボックス内で MultiWidget を日、月、年とともに日付を表示するためにサブクラス化するウィジェットの例です。このウィジェットは MultiValueField ではなく DateField とともに使われることを意図しています。そして、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.

ビルトインのウィジェットLink to this heading

Django は、全ての基本的な HTML ウィジェットの表現のほか、django.forms.widgets でいくつかの一般的に使われるウィジェットのグループを提供します。これは テキストの入力多種のチェックボックスおよび選択肢ファイルアップロード複数値の入力の扱い を含みます。

テキストの入力を扱うウィジェットLink to this heading

これらのウィジェットは、 inputtextarea の HTML 要素を使います。

TextInputLink to this heading

class TextInputLink to this definition
  • input_type: 'text'

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

  • Renders as: <input type="text" ...>

NumberInputLink to this heading

class NumberInputLink to this definition
  • input_type: 'number'

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

  • Renders as: <input type="number" ...>

全てのブラウザが number input タイプへローカライズされた数値を入力することをサポートしていない点に注意してください。Django 自身、localize プロパティが True にセットされたフィールドでは、これらを使用しません。

EmailInputLink to this heading

class EmailInputLink to this definition
  • input_type: 'email'

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

  • Renders as: <input type="email" ...>

URLInputLink to this heading

class URLInputLink to this definition
  • input_type: 'url'

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

  • Renders as: <input type="url" ...>

PasswordInputLink to this heading

class PasswordInputLink to this definition
  • input_type: 'password'

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

  • Renders as: <input type="password" ...>

1 つの省略可能な引数を取ります:

render_valueLink to this definition

バリデーションエラーの後、フォームが再描画されるときにウィジェットに値を書き込むかどうかを決めます (デフォルトは False です)。

HiddenInputLink to this heading

class HiddenInputLink to this definition
  • input_type: 'hidden'

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

  • Renders as: <input type="hidden" ...>

hidden の Input 要素のセットをカプセル化する MultipleHiddenInput ウィジェットもあります。

DateInputLink to this heading

class DateInputLink to this definition
  • input_type: 'text'

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

  • Renders as: <input type="text" ...>

TextInput と同じ引数を取り、さらに 1 つ省略可能な引数があります:

formatLink to this definition

このフィールドの初期値が描画されるフォーマットです。

format 引数が渡されないとき、デフォルトのフォーマットは DATE_INPUT_FORMATS 内で最初に見つかったフォーマットで、表示形式のローカル化 を尊重します。

DateTimeInputLink to this heading

class DateTimeInputLink to this definition
  • input_type: 'text'

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

  • Renders as: <input type="text" ...>

TextInput と同じ引数を取り、さらに 1 つ省略可能な引数があります:

formatLink to this definition

このフィールドの初期値が描画されるフォーマットです。

format 引数が渡されないとき、デフォルトのフォーマットは DATETIME_INPUT_FORMATS 内で最初に見つかったフォーマットで、表示形式のローカル化 を尊重します。

デフォルトでは、時刻のマイクロ秒部分は常に 0 にセットされます。マイクロ秒が必要な場合は、サブクラスで supports_microseconds 属性を True にセットして使ってください。

TimeInputLink to this heading

class TimeInputLink to this definition
  • input_type: 'text'

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

  • Renders as: <input type="text" ...>

TextInput と同じ引数を取り、さらに 1 つ省略可能な引数があります:

formatLink to this definition

このフィールドの初期値が描画されるフォーマットです。

format 引数が渡されないとき、デフォルトのフォーマットは TIME_INPUT_FORMATS 内で最初に見つかったフォーマットで、表示形式のローカル化 を尊重します。

マイクロ秒の扱いについては、DateTimeInput を参照してください。

TextareaLink to this heading

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

  • Renders as: <textarea>...</textarea>

セレクタおよびチェックボックスのウィジェットLink to this heading

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

  • Renders as: <input type="checkbox" ...>

1 つの省略可能な引数を取ります:

check_testLink to this definition

CheckboxInput の値を受け取り、チェックボックスがチェックされる必要がある場合は True を返す callable です。

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'

  • Renders as: <select><option ...>...</select>

choicesLink to this definition

フォームのフィールドに choices 属性がない場合、この属性は省略可能です。この属性がある場合には、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'

'Unknown'、'Yes'、'No' の選択肢ウィジェット

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'

Similar to Select, but allows multiple selection: <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'

Select`と似ているが ``<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 %}

This would generate the following HTML:

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 %}

...will result in the following HTML:

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'

Similar to SelectMultiple, but rendered as a list of checkboxes:

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.

ファイルアップロード用ウィジェットLink to this heading

FileInputLink to this heading

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

  • Renders as: <input type="file" ...>

ClearableFileInputLink to this heading

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

  • Renders as: <input type="file" ...> with an additional checkbox input to clear the field's value, if the field is not required and has initial data.

複合ウィジェットLink to this heading

MultipleHiddenInputLink to this heading

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

  • Renders as: multiple <input type="hidden" ...> tags

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

choicesLink to this definition

フォームのフィールドに choices 属性がない場合、この属性は省略可能です。この属性がある場合には、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 has several optional arguments:

date_formatLink to this definition

attr:DateInput.format と同様。

time_formatLink to this definition

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'

Similar to SplitDateTimeWidget, but uses HiddenInput for both date and time.

SelectDateWidgetLink to this heading

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

Wrapper around three Select widgets: one each for month, day, and year.

Takes several optional arguments:

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

If the DateField is not required, SelectDateWidget will have an empty choice at the top of the list (which is --- by default). You can change the text of this label with the empty_label attribute. empty_label can be a string, list, or tuple. When a string is used, all select boxes will each have an empty choice with this label. If empty_label is a list or tuple of 3 string elements, the select boxes will have their own custom label. The labels should be in this order ('year_label', 'month_label', 'day_label').

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