---
title: "ウィジェット"
version: 2.0
locale: ja
source: https://docs.djangoproject.com/ja/2.0/ref/forms/widgets/
canonical: https://djangodocs.dev/ja/2.0/ref/forms/widgets/
---
# ウィジェット

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

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

> **Tip**
>
> ウィジェットを [form fields](/ja/2.0/ref/forms/fields/) と混同しないでください。フォームフィールドは入力値の検証ロジックを扱い、テンプレート内で直接使用されます。ウィジェットはウェブページ上で input 要素から HTML の form をレンダリングし、submit された生データを取り出します。ウィジェットはフォームフィールドにアサイン ([assigned](#widget-to-field)) される必要があります。

## ウィジェットを指定する

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

フィールドに異なるウィジェットを使いたい場合は、フィールドを定義するときに [`widget`](/ja/2.0/ref/forms/fields/#django.forms.Field.widget) 引数を使うことができます。例えば:

```
from django import forms

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

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

## ウィジェットの引数を設定する

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

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

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

## `Select` ウィジェットを継承したウィジェット

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

[`Select`](#django.forms.Select) ウィジェットは、 [`ChoiceField`](/ja/2.0/ref/forms/fields/#django.forms.ChoiceField) フィールド上でデフォルトで使われます。

```
>>> 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`](#django.forms.Select.choices) 属性を提供するウィジェットは、選択肢に基づかないフィールド -- 例えば [`CharField`](/ja/2.0/ref/forms/fields/#django.forms.CharField)  -- とともに使うことができますが、選択肢がモデルに継承され、単に表示されるだけのウィジェットではないときには、[`ChoiceField`](/ja/2.0/ref/forms/fields/#django.forms.ChoiceField) に基づいたフィールドを使うことをお勧めします。

## ウィジェットのインスタンスをカスタマイズする

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

ウィジェットをカスタマイズする方法には 2 つあります: [ウィジェットごとのインスタンス](#styling-widget-instances) と [ウィジェットごとのクラス](#styling-widget-classes) です。

### ウィジェットのインスタンスにスタイルを設定する

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

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

```
from django import forms

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

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

```
>>> 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`](#django.forms.Widget.attrs) 引数を使います:

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

```
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`](/ja/2.0/ref/forms/api/#django.forms.Form.fields) attribute:

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

```
>>> 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`](#django.forms.Widget.attrs) を使った HTML の `id` をセットすることもできます。[`BoundField.id_for_label`](/ja/2.0/ref/forms/api/#django.forms.BoundField.id_for_label) で例をご覧ください。

### ウィジェットのクラスにスタイルを設定する

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

要するに、ウィジェットをサブクラス化して、 ["Media" 内部クラスの定義](/ja/2.0/topics/forms/media/#assets-as-a-static-definition) か ["media" プロパティの作成](/ja/2.0/topics/forms/media/#dynamic-property) のどちらかをする必要があります。

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

## ウィジェットの base クラス

[`Widget`](#django.forms.Widget) や [`MultiWidget`](#django.forms.MultiWidget) といった基本ウィジェットは、[ビルトインのウィジェット](#built-in-widgets) によってサブクラス化され、カスタムウィジェットのための基礎となります。

### `ウィジェット`

#### `class Widget(attrs=None)`

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

#### `attrs`

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

```pycon
>>> 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" />'
```

`True` か `False` の値を割り当てた場合は、HTML5 の ブール属性としてレンダリングされます。

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

`True` をデフォルト値にする属性です。`False` にセットされた場合は、[`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) と [`time`](https://docs.python.org/3/library/datetime.html#datetime.time) のマイクロ秒の部分の値は、`0` にセットされます。

#### `format_value(value)`

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

#### `get_context(name, value, attrs)`

> **New in Django 1.11**

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()`](#django.forms.Widget.format_value).
- `'attrs'`: HTML attributes to be set on the rendered widget. The
  combination of the [`attrs`](#django.forms.Widget.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_)`

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

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

#### `render(name, value, attrs=None, renderer=None)`

Renders a widget to HTML using the given renderer. If `renderer` is
`None`, the renderer from the [`FORM_RENDERER`](/ja/2.0/ref/settings/#std-setting-FORM_RENDERER) setting is
used.

> **Changed in Django 1.11**
>
> The `renderer` argument was added. Support for subclasses that
> don't accept it will be removed in Django 2.1.

#### `value_from_datadict(data, files, name)`

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

#### `value_omitted_from_data(data, files, name)`

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

メソッドの結果は、モデルフォームのフィールドが [デフォルトに逆戻りする](/ja/2.0/topics/forms/modelforms/#topics-modelform-save) かどうかに影響します。

Special cases are [`CheckboxInput`](#django.forms.CheckboxInput),
[`CheckboxSelectMultiple`](#django.forms.CheckboxSelectMultiple), and
[`SelectMultiple`](#django.forms.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)`

フォームフィールドの `初期の` 値が与えられ、ウィジェットが `必要な` HTML 属性とともにレンダリングできるかどうかを返します。フォームは、各フィールドに `必要な` 属性を描画するかどうかを決定するために、[`Field.required`](/ja/2.0/ref/forms/fields/#django.forms.Field.required) と [`Form.use_required_attribute`](/ja/2.0/ref/forms/api/#django.forms.Form.use_required_attribute) とともにこのメソッドを使います。

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

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

### `MultiWidget`

#### `class MultiWidget(widgets, attrs=None)`

複数のウィジェットで構成されたウィジェットです。[`MultiWidget`](#django.forms.MultiWidget) は [`MultiValueField`](/ja/2.0/ref/forms/fields/#django.forms.MultiValueField) と協調して動作します。

[`MultiWidget`](#django.forms.MultiWidget) には 1 つの必要な引数があります。

#### `widgets`

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

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

#### `decompress(value)`

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

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

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

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

```
from django.forms import MultiWidget

class SplitDateTimeWidget(MultiWidget):

    # ...

    def decompress(self, value):
        if value:
            return [value.date(), value.time().replace(microsecond=0)]
        return [None, None]
```

> **Tip**
>
> [`MultiValueField`](/ja/2.0/ref/forms/fields/#django.forms.MultiValueField) が、正反対の責務 - 全メンバーフィールドの整えられた値を 1 つにまとめること - を持つ補完メソッド [`compress()`](/ja/2.0/ref/forms/fields/#django.forms.MultiValueField.compress) を持っていることを覚えておいてください。

It provides some custom context:

#### `get_context(name, value, attrs)`

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

These can be looped over in the widget template:

```html+django
{% for subwidget in widget.subwidgets %}
    {% include widget.template_name with widget=subwidget %}
{% endfor %}
```

異なるセレクトボックス内で [`MultiWidget`](#django.forms.MultiWidget) を日、月、年とともに日付を表示するためにサブクラス化するウィジェットの例です。このウィジェットは [`MultiValueField`](/ja/2.0/ref/forms/fields/#django.forms.MultiValueField) ではなく [`DateField`](/ja/2.0/ref/forms/fields/#django.forms.DateField) とともに使われることを意図しています。そして、[`value_from_datadict()`](#django.forms.Widget.value_from_datadict) が実行されています:

```
from datetime import date
from django.forms import widgets

class DateSelectorWidget(widgets.MultiWidget):
    def __init__(self, attrs=None):
        # create choices for days, months, years
        # example below, the rest snipped for brevity.
        years = [(year, year) for year in (2011, 2012, 2013)]
        _widgets = (
            widgets.Select(attrs=attrs, choices=days),
            widgets.Select(attrs=attrs, choices=months),
            widgets.Select(attrs=attrs, choices=years),
        )
        super().__init__(_widgets, attrs)

    def decompress(self, value):
        if value:
            return [value.day, value.month, value.year]
        return [None, None, None]

    def value_from_datadict(self, data, files, name):
        datelist = [
            widget.value_from_datadict(data, files, name + '_%s' % i)
            for i, widget in enumerate(self.widgets)]
        try:
            D = date(
                day=int(datelist[0]),
                month=int(datelist[1]),
                year=int(datelist[2]),
            )
        except ValueError:
            return ''
        else:
            return str(D)
```

コンストラクタは、タプル内に複数の [`Select`](#django.forms.Select) ウィジェットを作成します。`super` クラスは、このタプルをウィジェットをセットアップするために使います。

必要なメソッド [`decompress()`](#django.forms.MultiWidget.decompress) は `datetime.date` の値を各ウィジェットに対応する日、月、年の値に分解します。メソッドが、 `value` が `None` のケースをどのように扱うか覚えておいてください。

[`value_from_datadict()`](#django.forms.Widget.value_from_datadict) のデフォルトの処理は、各 `ウィジェット` に一致する値のリストを返します。`MultiWidget` を [`MultiValueField`](/ja/2.0/ref/forms/fields/#django.forms.MultiValueField) とともに使うときには適していますが、このウィジェットを単一の値を取る class:~django.forms.DateField とともに使いたいので、サブウィジェットのデータを `datetime.date` にまとめるようメソッドはオーバーライドされています。メソッドは `POST` ディクショナリからデータを展開し構成して、日付を検証します。値が適正な場合、文字列を返します。適正でなければ、 `form.is_valid` に `False` を返させるための空の文字列を返します。

## ビルトインのウィジェット

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

### テキストの入力を扱うウィジェット

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

#### `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" ...>`

全てのブラウザが `number` input タイプへローカライズされた数値を入力することをサポートしていない点に注意してください。Django 自身、[`localize`](/ja/2.0/ref/forms/fields/#django.forms.Field.localize) プロパティが `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" ...>`

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

#### `render_value`

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

#### `HiddenInput`

#### `class HiddenInput`

- `input_type`: `'hidden'`
- `template_name`: `'django/forms/widgets/hidden.html'`
- Renders as: `<input type="hidden" ...>`

hidden の Input 要素のセットをカプセル化する [`MultipleHiddenInput`](#django.forms.MultipleHiddenInput) ウィジェットもあります。

#### `DateInput`

#### `class DateInput`

- `input_type`: `'text'`
- `template_name`: `'django/forms/widgets/date.html'`
- Renders as: `<input type="text" ...>`

[`TextInput`](#django.forms.TextInput) と同じ引数を取り、さらに 1 つ省略可能な引数があります:

#### `format`

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

`format` 引数が渡されないとき、デフォルトのフォーマットは [`DATE_INPUT_FORMATS`](/ja/2.0/ref/settings/#std-setting-DATE_INPUT_FORMATS) 内で最初に見つかったフォーマットで、[表示形式のローカル化](/ja/2.0/topics/i18n/formatting/) を尊重します。

#### `DateTimeInput`

#### `class DateTimeInput`

- `input_type`: `'text'`
- `template_name`: `'django/forms/widgets/datetime.html'`
- Renders as: `<input type="text" ...>`

[`TextInput`](#django.forms.TextInput) と同じ引数を取り、さらに 1 つ省略可能な引数があります:

#### `format`

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

`format` 引数が渡されないとき、デフォルトのフォーマットは [`DATETIME_INPUT_FORMATS`](/ja/2.0/ref/settings/#std-setting-DATETIME_INPUT_FORMATS) 内で最初に見つかったフォーマットで、[表示形式のローカル化](/ja/2.0/topics/i18n/formatting/) を尊重します。

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

#### `TimeInput`

#### `class TimeInput`

- `input_type`: `'text'`
- `template_name`: `'django/forms/widgets/time.html'`
- Renders as: `<input type="text" ...>`

[`TextInput`](#django.forms.TextInput) と同じ引数を取り、さらに 1 つ省略可能な引数があります:

#### `format`

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

`format` 引数が渡されないとき、デフォルトのフォーマットは [`TIME_INPUT_FORMATS`](/ja/2.0/ref/settings/#std-setting-TIME_INPUT_FORMATS) 内で最初に見つかったフォーマットで、[表示形式のローカル化](/ja/2.0/topics/i18n/formatting/) を尊重します。

マイクロ秒の扱いについては、[`DateTimeInput`](#django.forms.DateTimeInput) を参照してください。

#### `Textarea`

#### `class Textarea`

- `template_name`: `'django/forms/widgets/textarea.html'`
- Renders as: `<textarea>...</textarea>`

### セレクタおよびチェックボックスのウィジェット

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`](#django.forms.Select) 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" ...>`

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

#### `check_test`

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

#### `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`

フォームのフィールドに `choices` 属性がない場合、この属性は省略可能です。この属性がある場合には、[`Field`](/ja/2.0/ref/forms/fields/#django.forms.Field) で属性が更新されたときにセットされた全てをオーバーライドします。

#### `NullBooleanSelect`

#### `class NullBooleanSelect`

- `template_name`: `'django/forms/widgets/select.html'`
- `option_template_name`: `'django/forms/widgets/select_option.html'`

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

#### `SelectMultiple`

#### `class SelectMultiple`

- `template_name`: `'django/forms/widgets/select.html'`
- `option_template_name`: `'django/forms/widgets/select_option.html'`

Similar to [`Select`](#django.forms.Select), but allows multiple selection:
`<select multiple="multiple">...</select>`

#### `RadioSelect`

#### `class RadioSelect`

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

```html+django
{% 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...

```html+django
{% 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`](/ja/2.0/ref/forms/api/#django.forms.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.

#### `CheckboxSelectMultiple`

#### `class CheckboxSelectMultiple`

- `template_name`: `'django/forms/widgets/checkbox_select.html'`
- `option_template_name`: `'django/forms/widgets/checkbox_option.html'`

Similar to [`SelectMultiple`](#django.forms.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`](/ja/2.0/ref/forms/api/#django.forms.BoundField.auto_id) otherwise.

Like [`RadioSelect`](#django.forms.RadioSelect), you can loop over the individual checkboxes for the
widget's choices. Unlike [`RadioSelect`](#django.forms.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.

### ファイルアップロード用ウィジェット

#### `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 checkbox
  input to clear the field's value, if the field is not required and has
  initial data.

### 複合ウィジェット

#### `MultipleHiddenInput`

#### `class MultipleHiddenInput`

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

#### `choices`

フォームのフィールドに `choices` 属性がない場合、この属性は省略可能です。この属性がある場合には、[`Field`](/ja/2.0/ref/forms/fields/#django.forms.Field) で属性が更新されたときにセットされた全てをオーバーライドします。

#### `SplitDateTimeWidget`

#### `class SplitDateTimeWidget`

- `template_name`: `'django/forms/widgets/splitdatetime.html'`

Wrapper (using [`MultiWidget`](#django.forms.MultiWidget)) around two widgets: [`DateInput`](#django.forms.DateInput)
for the date, and [`TimeInput`](#django.forms.TimeInput) for the time. Must be used with
[`SplitDateTimeField`](/ja/2.0/ref/forms/fields/#django.forms.SplitDateTimeField) rather than [`DateTimeField`](/ja/2.0/ref/forms/fields/#django.forms.DateTimeField).

`SplitDateTimeWidget` has several optional arguments:

#### `date_format`

attr:DateInput.format と同様。

#### `time_format`

[`TimeInput.format`](#django.forms.TimeInput.format) と同様

#### `date_attrs`

#### `time_attrs`

> **New in Django 2.0**

Similar to [`Widget.attrs`](#django.forms.Widget.attrs). A dictionary containing HTML
attributes to be set on the rendered [`DateInput`](#django.forms.DateInput) and
[`TimeInput`](#django.forms.TimeInput) widgets, respectively. If these attributes aren't
set, [`Widget.attrs`](#django.forms.Widget.attrs) is used instead.

#### `SplitHiddenDateTimeWidget`

#### `class SplitHiddenDateTimeWidget`

- `template_name`: `'django/forms/widgets/splithiddendatetime.html'`

Similar to [`SplitDateTimeWidget`](#django.forms.SplitDateTimeWidget), but uses [`HiddenInput`](#django.forms.HiddenInput) for
both date and time.

#### `SelectDateWidget`

#### `class SelectDateWidget`

- `template_name`: `'django/forms/widgets/select_date.html'`

Wrapper around three [`Select`](#django.forms.Select) widgets: one each for
month, 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) and
the values are the displayed months:

```
MONTHS = {
    1:_('jan'), 2:_('feb'), 3:_('mar'), 4:_('apr'),
    5:_('may'), 6:_('jun'), 7:_('jul'), 8:_('aug'),
    9:_('sep'), 10:_('oct'), 11:_('nov'), 12:_('dec')
}
```

#### `empty_label`

If the [`DateField`](/ja/2.0/ref/forms/fields/#django.forms.DateField) is not required,
[`SelectDateWidget`](#django.forms.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"),
    ),
)
```
