---
title: "フォーム API"
version: 4.1
locale: ja
source: https://docs.djangoproject.com/ja/4.1/ref/forms/api/
canonical: https://djangodocs.dev/ja/4.1/ref/forms/api/
---
# フォーム API

> **このドキュメントについて**
>
> このドキュメントでは、Django のフォーム API の詳細について説明します。このドキュメントを読む前に introduction to working with forms 1 を読むことをおすすめします。

## Bound and unbound forms

[`Form`](#django.forms.Form) インスタンスには、データに\*\*くくりつけられた\*\* ものと **くくりつけられていない** ものがあります。

- データに **くくりつけられた** [`Form`](#django.forms.Form) インスタンスは、そのデータを検証したり、HTMLフォームとしてレンダリングしてHTMLに表示することができます。
- **くくりつけられていない** [`Form`](#django.forms.Form) インスタンスは、データを検証することができません（なぜなら、検証するデータがないから！）が、空のフォームをHTMLとしてレンダリングすることは可能です。

#### `class Form`

くくりつけられていない [`Form`](#django.forms.Form) インスタンスを作るには、クラスをインスタンス化します:

```
>>> f = ContactForm()
```

データをフォームにくくりつけるには、データをディクショナリとして [`Form`](#django.forms.Form) クラスのコンストラクタの第1引数に渡します:

```
>>> data = {'subject': 'hello',
...         'message': 'Hi there',
...         'sender': 'foo@example.com',
...         'cc_myself': True}
>>> f = ContactForm(data)
```

このディクショナリでは、キーは [`Form`](#django.forms.Form)  の属性に対応するフィールド名で、値は検証したいデータです。これらはふつう文字列ですが、文字列でなければならないという決まりはありません; あとですぐ見るように、渡すデータの型は [`Field`](/ja/4.1/ref/forms/fields/#django.forms.Field) によって決まります。

#### `Form.is_bound`

フォームインスタンスがくくりつけられているかいないかを実行中に見分けたい場合は、フォームの `is_bount` 属性の値を使用します:

```
>>> f = ContactForm()
>>> f.is_bound
False
>>> f = ContactForm({'subject': 'hello'})
>>> f.is_bound
True
```

空のディクショナリを渡した場合は、空のデータをもつ *くくりつけられた* フォームインスタンスになることに注意してください:

```
>>> f = ContactForm({})
>>> f.is_bound
True
```

[`Form`](#django.forms.Form) インスタンスの中のデータを書き換える方法はありません。一度 [`Form`](#django.forms.Form) インスタンスを作成したら、データを持っていようがいまいが、それはイミュータブルだと考えてください。もし、bound な [`Form`](#django.forms.Form) インスタンスのデータをなんとかして変更したかったり、unbound な [`Form`](#django.forms.Form) インスタンスにデータをくくりつけたいような場合は、 [`Form`](#django.forms.Form) インスタンスを新たに作成します。

## フォームをデータの検証に使用する

#### `Form.clean()`

相互に関連のあるフィールドに対して独自のバリデーションを追加する必要がある場合、`Form` 上で `clean()` を実装してください。具体的な使用方法は [互いに依存するフィールドをクリーニングして検証する](/ja/4.1/ref/forms/validation/#validating-fields-with-clean) を参照してください。

#### `Form.is_valid()`

[`Form`](#django.forms.Form) オブジェクトの最重要タスクは、データを検証することです。bound な [`Form`](#django.forms.Form) インスタンスにおいて、[`is_valid()`](#django.forms.Form.is_valid) メソッドを呼び出してバリデーションを実行し、データが有効だったかどうかを示す真偽値を返してください:

```
>>> data = {'subject': 'hello',
...         'message': 'Hi there',
...         'sender': 'foo@example.com',
...         'cc_myself': True}
>>> f = ContactForm(data)
>>> f.is_valid()
True
```

無効なデータを試してみましょう。この例では、`subject` が空白で (すべてのフィールドはデフォルトで必須なのでラーとなります) `sender` が無効なメールアドレスです:

```
>>> data = {'subject': '',
...         'message': 'Hi there',
...         'sender': 'invalid email address',
...         'cc_myself': True}
>>> f = ContactForm(data)
>>> f.is_valid()
False
```

#### `Form.errors`

エラーメッセージのディクショナリを使用するには、[`errors`](#django.forms.Form.errors) 属性にアクセスしてください:

```
>>> f.errors
{'sender': ['Enter a valid email address.'], 'subject': ['This field is required.']}
```

このディクショナリでは、キーはフィールド名、値はエラーメッセージを表す文字列のリストです。エラーメッセージがリストに格納されるのは、1 つのフィールドに複数のエラーメッセージがある可能性があるからです。

[`is_valid()`](#django.forms.Form.is_valid) を呼び出す前に [`errors`](#django.forms.Form.errors) にアクセスすることもできます。フォームのデータは、最初に [`is_valid()`](#django.forms.Form.is_valid) を呼び出したり [`errors`](#django.forms.Form.errors) にアクセスすることで検証されます。

バリデーションのルーチンは、[`errors`](#django.forms.Form.errors) や call [`is_valid()`](#django.forms.Form.is_valid) を何度呼び出しても 1 度だけ呼び出されます。これが意味するのは、もしバリデーションが副作用を持っている場合、その副作用は 1 度だけ発生すると言うことです。

#### `Form.errors.as_data()`

フィールドとオリジナルの `ValidationError` インスタンスをマッピングする `dict` を返します。

```
>>> f.errors.as_data()
{'sender': [ValidationError(['Enter a valid email address.'])],
'subject': [ValidationError(['This field is required.'])]}
```

`code` によりエラーを特定する必要があるときはこのメソッドを使用してください。これによって、エラーメッセージの上書きや、エラーが存在するときのビューでの独自のロジックが作成できるようになります。独自のフォーマット (例えば XML) でシリアライズするためにも使えます; 例えば [`as_json()`](#django.forms.Form.errors.as_json) は `as_data()` を利用しています。

`as_data()` の必要性は、後方互換性に起因します。以前は `ValidationError` インスタンスは **描画された** エラーメッセージが `Form.errors` ディクショナリに追加されると同時に消失していました。できれば `Form.errors` が `ValidationError` インスタンスを保持し、`as_` プレフィクスを伴うメソッドがエラーを描画できるのが理想でしたが、`Form.errors` 内の描画されたエラーメッセージを受け取る可能性があるコードを壊さないために、逆の実装にしなくてはなりませんでした。

#### `Form.errors.as_json(escape_html=False)`

Returns the errors serialized as JSON.

```
>>> f.errors.as_json()
{"sender": [{"message": "Enter a valid email address.", "code": "invalid"}],
"subject": [{"message": "This field is required.", "code": "required"}]}
```

By default, `as_json()` does not escape its output. If you are using it for
something like AJAX requests to a form view where the client interprets the
response and inserts errors into the page, you'll want to be sure to escape the
results on the client-side to avoid the possibility of a cross-site scripting
attack. You can do this in JavaScript with `element.textContent = errorText`
or with jQuery's `$(el).text(errorText)` (rather than its `.html()`
function).

If for some reason you don't want to use client-side escaping, you can also
set `escape_html=True` and error messages will be escaped so you can use them
directly in HTML.

#### `Form.errors.get_json_data(escape_html=False)`

Returns the errors as a dictionary suitable for serializing to JSON.
[`Form.errors.as_json()`](#django.forms.Form.errors.as_json) returns serialized JSON, while this returns the
error data before it's serialized.

The `escape_html` parameter behaves as described in
[`Form.errors.as_json()`](#django.forms.Form.errors.as_json).

#### `Form.add_error(field, error)`

This method allows adding errors to specific fields from within the
`Form.clean()` method, or from outside the form altogether; for instance
from a view.

`field` 引数にはエラーを追加したいフィールド名を指定します。この値が `None` の場合、 [`Form.non_field_errors()`](#django.forms.Form.non_field_errors) によって返されるようなフィールドによらないエラーとして扱われます。

フォームエラーを定義するときのベストプラクティスとして、 `error` 引数は文字列もしくは、できれば `ValidationError` のインスタンスを指定します。フォームエラーの定義時のベストプラクティスについては、 [ValidationError を発生させる](/ja/4.1/ref/forms/validation/#raising-validation-error) を参照してください。

`Form.add_error()` は `cleaned_data` からフィールドを自動的に削除してしまうことに注意してください。

#### `Form.has_error(field, code=None)`

このメソッドは指定したフィールドが特定の `code` のエラーを持つか否かを真偽値で返します。`code` が `None` の場合、そのフィールドにエラーが一つもない場合に `True` を返します。

フィールドによらないエラー (non-field errors) の有無を確認したい場合は、`field` 引数に [`NON_FIELD_ERRORS`](/ja/4.1/ref/exceptions/#django.core.exceptions.NON_FIELD_ERRORS) を渡します。

#### `Form.non_field_errors()`

このメソッドは [`Form.errors`](#django.forms.Form.errors) から、特定のフィールドに関連付けられていないエラーのリストを返します。これには、 [`Form.clean()`](#django.forms.Form.clean) で発生された `ValidationError` と、 [`Form.add_error(None, "...")`](#django.forms.Form.add_error) で追加されたエラーが含まれます。

### くくりつけられていないフォームの挙動

データのないフォームを検証することに意味はありませんが、念のため、くくりつけられていないフォームでは何が起こるかを記しておきます:

```
>>> f = ContactForm()
>>> f.is_valid()
False
>>> f.errors
{}
```

## Initial form values

#### `Form.initial`

[`initial`](#django.forms.Form.initial) を使うことで、実行時にフォームの初期値を設定することができます。たとえば、 `username` フォームを埋めるのに、現在のセッションの username を使うことができます。

このためには、 [`Form`](#django.forms.Form) の [`initial`](#django.forms.Form.initial) 引数を使います。この引数を渡す場合、フィールド名と初期値をマッピングしたディクショナリで渡します。渡すのは初期値を設定したいフィールドだけです; すべてのフィールドを指定する必要はありません。例えば:

```
>>> f = ContactForm(initial={'subject': 'Hi there!'})
```

これらの値はくくりつけられていないフォームにたんに表示されるだけです。値が入力されなかった場合の予備値として使われることはありません。

もし [`Field`](/ja/4.1/ref/forms/fields/#django.forms.Field) の中で [`initial`](/ja/4.1/ref/forms/fields/#django.forms.Field.initial) が定義されていて、 *加えて* `Form` をインスタンス化する際に [`initial`](#django.forms.Form.initial) を引数にインクルードする場合、後者が優先されます。この例では、 `initial` がフィールドとフォームインスタンスの両方で指定されていますが、後者が優先されます:

```
>>> from django import forms
>>> class CommentForm(forms.Form):
...     name = forms.CharField(initial='class')
...     url = forms.URLField()
...     comment = forms.CharField()
>>> f = CommentForm(initial={'name': 'instance'}, auto_id=False)
>>> print(f)
<tr><th>Name:</th><td><input type="text" name="name" value="instance" 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>
```

#### `Form.get_initial_for_field(field, field_name)`

Returns the initial data for a form field. It retrieves the data from
[`Form.initial`](#django.forms.Form.initial) if present, otherwise trying [`Field.initial`](/ja/4.1/ref/forms/fields/#django.forms.Field.initial).
Callable values are evaluated.

It is recommended to use [`BoundField.initial`](#django.forms.BoundField.initial) over
[`get_initial_for_field()`](#django.forms.Form.get_initial_for_field) because `BoundField.initial` has a
simpler interface. Also, unlike [`get_initial_for_field()`](#django.forms.Form.get_initial_for_field),
[`BoundField.initial`](#django.forms.BoundField.initial) caches its values. This is useful especially when
dealing with callables whose return values can change (e.g. `datetime.now` or
`uuid.uuid4`):

```
>>> import uuid
>>> class UUIDCommentForm(CommentForm):
...     identifier = forms.UUIDField(initial=uuid.uuid4)
>>> f = UUIDCommentForm()
>>> f.get_initial_for_field(f.fields['identifier'], 'identifier')
UUID('972ca9e4-7bfe-4f5b-af7d-07b3aa306334')
>>> f.get_initial_for_field(f.fields['identifier'], 'identifier')
UUID('1b411fab-844e-4dec-bd4f-e9b0495f04d0')
>>> # Using BoundField.initial, for comparison
>>> f['identifier'].initial
UUID('28a09c59-5f00-4ed9-9179-a3b074fa9c30')
>>> f['identifier'].initial
UUID('28a09c59-5f00-4ed9-9179-a3b074fa9c30')
```

## どのフォームデータが変更されたかをチェックする

#### `Form.has_changed()`

フォームデータが初期値から変更されたかどうかをチェックしたい場合は、 `has_changed()` メソッドを使います。

```
>>> data = {'subject': 'hello',
...         'message': 'Hi there',
...         'sender': 'foo@example.com',
...         'cc_myself': True}
>>> f = ContactForm(data, initial=data)
>>> f.has_changed()
False
```

フォームが送信された場合、比較ができるようにフォームを再構築して元のデータを提供します:

```
>>> f = ContactForm(request.POST, initial=data)
>>> f.has_changed()
```

`has_changed()` は、 `request.POST` が [`initial`](#django.forms.Form.initial) で提供されたデータと異なる場合、 `True` を返し、同じであれば `False` を返します。この結果は、それぞれのフィールドで [`Field.has_changed()`](/ja/4.1/ref/forms/fields/#django.forms.Field.has_changed) を呼ぶことで計算されます。

#### `Form.changed_data`

`changed_data` 属性は、フォームにくくりつけられたデータ (ふつうは `request.POST`) の値が [`initial`](#django.forms.Form.initial) で提供されたものと異なるとき、そのフィールド名のリストを返します。データが変更されていない場合は、空のリストを返します。

```
>>> f = ContactForm(request.POST, initial=data)
>>> if f.has_changed():
...     print("The following fields changed: %s" % ", ".join(f.changed_data))
>>> f.changed_data
['subject', 'message']
```

## フォームからフィールドにアクセスする

#### `Form.fields`

[`Form`](#django.forms.Form) のフィールドには、その `fields` 属性を通してアクセスすることができます:

```
>>> for row in f.fields.values(): print(row)
...
<django.forms.fields.CharField object at 0x7ffaac632510>
<django.forms.fields.URLField object at 0x7ffaac632f90>
<django.forms.fields.CharField object at 0x7ffaac3aa050>
>>> f.fields['name']
<django.forms.fields.CharField object at 0x7ffaac6324d0>
```

You can alter the field and [`BoundField`](#django.forms.BoundField) of [`Form`](#django.forms.Form) instance to
change the way it is presented in the form:

```
>>> f.as_div().split("</div>")[0]
'<div><label for="id_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_subject">'
>>> f["subject"].label = "Topic"
>>> f.as_div().split("</div>")[0]
'<div><label for="id_subject">Topic:</label><input type="text" name="subject" maxlength="100" required id="id_subject">'
```

`base_fields` 属性は変更しないように気をつけてください。なぜなら、同じ Python プロセス内であとに続くすべての `ContactForm` に影響を与えることになるためです。

```
>>> f.base_fields["subject"].label_suffix = "?"
>>> another_f = CommentForm(auto_id=False)
>>> f.as_div().split("</div>")[0]
'<div><label for="id_subject">Subject?</label><input type="text" name="subject" maxlength="100" required id="id_subject">'
```

## "clean" なデータにアクセスする

#### `Form.cleaned_data`

[`Form`](#django.forms.Form) クラスのそれぞれのフィールドは、データの検証のみならず、データの "cleaning" -- 整合性のある形式に正規化すること -- にも責任を持ちます。これは素晴らしい機能です。なぜなら、様々な形式で入力されるフィールドのデータから、いつでも整合性のある出力が得られるようになるからです。

たとえば、 [`DateField`](/ja/4.1/ref/forms/fields/#django.forms.DateField) はインプットを Python の `datetime.date` オブジェクトに正規化します。たとえ `'1994-07-15'` という形式の文字列で渡そうが、 `datetime.date` オブジェクトを渡そうが、他の様々な形式で渡そうが、それが検証にパスする限り `DateField` はいつも `datetime.date` オブジェクトに正規化します。

あるデータのセットに対して、いちど [`Form`](#django.forms.Form) インスタンスを作成して検証したら、`cleaned_data` 属性を通してクリーンなデータにアクセスすることができます:

```
>>> data = {'subject': 'hello',
...         'message': 'Hi there',
...         'sender': 'foo@example.com',
...         'cc_myself': True}
>>> f = ContactForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data
{'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}
```

`CharField` や `EmailField` といったテキストベースのフィールドは、入力を文字列に正規化します。暗黙的な文字エンコードの挙動については、後のドキュメントでカバーします。

データが検証をパス **しなかった**  場合、 `cleaned_data` ディクショナリは検証にパスしたフィールドだけを含みます。

```
>>> data = {'subject': '',
...         'message': 'Hi there',
...         'sender': 'invalid email address',
...         'cc_myself': True}
>>> f = ContactForm(data)
>>> f.is_valid()
False
>>> f.cleaned_data
{'cc_myself': True, 'message': 'Hi there'}
```

`cleaned_data` いつも、 `Form` で定義されたフィールド *だけ* をキーとして持ちます。たとえ `Form` を定義するときに余分なデータを渡していたとしても無視されます。この例では、いくつかの余分なフィールドを `ContactForm` コンストラクタに渡していますが、 `cleaned_data` はフォームのフィールドしか持っていません:

```
>>> data = {'subject': 'hello',
...         'message': 'Hi there',
...         'sender': 'foo@example.com',
...         'cc_myself': True,
...         'extra_field_1': 'foo',
...         'extra_field_2': 'bar',
...         'extra_field_3': 'baz'}
>>> f = ContactForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data # Doesn't contain extra_field_1, etc.
{'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}
```

`Form` が検証をパスした場合、 `cleaned_data` は、省略可能なフィールドに値が入っていなかったとしても、 *すべての* フィールドのキーと値をインクルードします。この例では、データディクショナリは `nick_name` フィールドに値をインクルードしていませんが、 `cleaned_data` には空の値を伴ってインクルードされています:

```
>>> from django import forms
>>> class OptionalPersonForm(forms.Form):
...     first_name = forms.CharField()
...     last_name = forms.CharField()
...     nick_name = forms.CharField(required=False)
>>> data = {'first_name': 'John', 'last_name': 'Lennon'}
>>> f = OptionalPersonForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data
{'nick_name': '', 'first_name': 'John', 'last_name': 'Lennon'}
```

上の例では、 `cleaned_data` 中の `nick_name` の値には空の文字列がセットされています。これは、 `nick_name` が `CharField` であり、 `CharField` は空の値を空の文字列として扱うからです。それぞれのフィールドタイプは、それぞれの `空の` 値が何であるか知っています -- たとえば、 `DateField` では空の文字列の代わりに `None` です。それぞれのフィールドの挙動の完全な詳細は、あとの "Built-in `Field` classes" セクションにある "Empty value" ノートを見てください。

特定のいくつかの (フォーム名に基づく) フォームフィールドまたは (さまざまなフィールドの組み合わせを考えて) フォーム全体に対しての検証を行うコードを書くことも可能です。これについての詳細は、 [フォームとフィールドの検証](/ja/4.1/ref/forms/validation/) を見てください。

## フォームをHTMLとしてアウトプットする

`Form` オブジェクトの 2 番目のタスクは、それ自身をHTMLとしてレンダリングすることです。そうするには `print` します:

```
>>> f = ContactForm()
>>> print(f)
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr>
<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr>
<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr>
```

フォームがデータにくくりつけられている場合、 HTML アウトプットはデータを適切にインクルードします。たとえば、フィールドタイプが `<input type="text">` で表される場合、データは `value` 属性に入ります。フィールドが `<input type="checkbox">` で表される場合、それが適当なであれば HTML は `checked` をインクルードします:

```
>>> data = {'subject': 'hello',
...         'message': 'Hi there',
...         'sender': 'foo@example.com',
...         'cc_myself': True}
>>> f = ContactForm(data)
>>> print(f)
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" value="hello" required></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" value="Hi there" required></td></tr>
<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" value="foo@example.com" required></td></tr>
<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" checked></td></tr>
```

デフォルトのアウトプットは `<tr>` をそれぞれのフィールドに伴う 2 カラムの HTML テーブルです。注意点としては:

- 柔軟性のため、アウトプットは `<table>` `</table>` タグをインクルードしません。また、 `<form>` `</form>` タグや `<input type="submit">` タグもインクルードされません。これらはあなたの仕事です。
- それぞれのフィールドタイプはデフォルトの HTML 表現を持っています。 `CharField` は `<input type="text">` で、 `EmailField` は `<input type="email">` で表現され、`BooleanField(null=False)` は `<input type="checkbox">` で表現されます。これらは単なる実用的なデフォルトであり、あるフィールドにどの HTML を使うかは、すぐ後で説明するウィジェットを使って指定することができます。
- HTML のそれぞれのタグの `name` は、 `ContactForm` クラスの属性名から直接とられます。
- それぞれのフィールドのテキストラベル、たとえば `'Subject:'`, `'Message:'` , `'Cc myself:'` は、フィールド名のアンダースコアをスペースに変換し、頭文字を大文字に変換して生成されます。これらもまた単なる実用的なデフォルトです; 手動でラベルを指定することもできます。
- それぞれのテキストラベルは HTML `<label>` タグで囲まれており、 `id` を通して適切なフォームフィールドを指しています。`id` は、フィールド名に `'id_'` を前置することで生成されます。`id` 属性と `<label>` タグは、ベストプラクティスに従ってデフォルトでアウトプットにインクルードされますが、この挙動も変更することができます。
- The output uses HTML5 syntax, targeting `<!DOCTYPE html>`. For example,
  it uses boolean attributes such as `checked` rather than the XHTML style
  of `checked='checked'`.

`<table>` アウトプットがフォームを `print` したときのデフォルトではあるものの、他のアウトプットスタイルも利用可能です。それぞれのスタイルはフォームオブジェクトのメソッドとして利用可能で、それぞれのメソッドは文字列を返します。

### Default rendering

The default rendering when you `print` a form uses the following methods and
attributes.

#### `template_name`

> **New in Django 4.0**

#### `Form.template_name`

The name of the template rendered if the form is cast into a string, e.g. via
`print(form)` or in a template via `{{ form }}`.

By default, a property returning the value of the renderer's
[`form_template_name`](/ja/4.1/ref/forms/renderers/#django.forms.renderers.BaseRenderer.form_template_name). You may set it
as a string template name in order to override that for a particular form
class.

> **Changed in Django 4.1**
>
> In older versions `template_name` defaulted to the string value
> `'django/forms/default.html'`.

#### `render()`

> **New in Django 4.0**

#### `Form.render(template_name=None, context=None, renderer=None)`

The render method is called by `__str__` as well as the
[`Form.as_table()`](#django.forms.Form.as_table), [`Form.as_p()`](#django.forms.Form.as_p), and [`Form.as_ul()`](#django.forms.Form.as_ul) methods.
All arguments are optional and default to:

- `template_name`: [`Form.template_name`](#django.forms.Form.template_name)
- `context`: Value returned by [`Form.get_context()`](#django.forms.Form.get_context)
- `renderer`: Value returned by [`Form.default_renderer`](#django.forms.Form.default_renderer)

By passing `template_name` you can customize the template used for just a
single call.

#### `get_context()`

> **New in Django 4.0**

#### `Form.get_context()`

Return the template context for rendering the form.

The available context is:

- `form`: The bound form.
- `fields`: All bound fields, except the hidden fields.
- `hidden_fields`: All hidden bound fields.
- `errors`: All non field related or hidden field related form errors.

#### `template_name_label`

> **New in Django 4.0**

#### `Form.template_name_label`

The template used to render a field's `<label>`, used when calling
[`BoundField.label_tag()`](#django.forms.BoundField.label_tag)/[`legend_tag()`](#django.forms.BoundField.legend_tag). Can be changed per
form by overriding this attribute or more generally by overriding the default
template, see also [Overriding built-in form templates](/ja/4.1/ref/forms/renderers/#overriding-built-in-form-templates).

### Output styles

As well as rendering the form directly, such as in a template with
`{{ form }}`, the following helper functions serve as a proxy to
[`Form.render()`](#django.forms.Form.render) passing a particular `template_name` value.

These helpers are most useful in a template, where you need to override the
form renderer or form provided value but cannot pass the additional parameter
to [`render()`](#django.forms.Form.render). For example, you can render a form as an unordered
list using `{{ form.as_ul }}`.

Each helper pairs a form method with an attribute giving the appropriate
template name.

#### `as_div()`

#### `Form.template_name_div`

> **New in Django 4.1**

The template used by `as_div()`. Default: `'django/forms/div.html'`.

#### `Form.as_div()`

> **New in Django 4.1**

`as_div()` renders the form as a series of `<div>` elements, with each
`<div>` containing one field, such as:

```pycon
>>> f = ContactForm()
>>> f.as_div()
```

… gives HTML like:

```html
<div>
<label for="id_subject">Subject:</label>
<input type="text" name="subject" maxlength="100" required id="id_subject">
</div>
<div>
<label for="id_message">Message:</label>
<input type="text" name="message" required id="id_message">
</div>
<div>
<label for="id_sender">Sender:</label>
<input type="email" name="sender" required id="id_sender">
</div>
<div>
<label for="id_cc_myself">Cc myself:</label>
<input type="checkbox" name="cc_myself" id="id_cc_myself">
</div>
```

> **Note**
>
> Of the framework provided templates and output styles, `as_div()` is
> recommended over the `as_p()`, `as_table()`, and `as_ul()` versions
> as the template implements `<fieldset>` and `<legend>` to group related
> inputs and is easier for screen reader users to navigate.

#### `as_p()`

#### `Form.template_name_p`

The template used by `as_p()`. Default: `'django/forms/p.html'`.

#### `Form.as_p()`

`as_p()` はフォームをいくつかの `<p>` タグとしてレンダリングします。ひとつの `<p>` はひとつのフィールドを含みます:

```
>>> f = ContactForm()
>>> f.as_p()
'<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></p>\n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></p>\n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" required></p>\n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></p>'
>>> print(f.as_p())
<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></p>
<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></p>
<p><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></p>
<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></p>
```

#### `as_ul()`

#### `Form.template_name_ul`

The template used by `as_ul()`. Default: `'django/forms/ul.html'`.

#### `Form.as_ul()`

`as_ul()` はフォームをいくつかの `<li>` タグとしてレンダリングします。ひとつの `<li>` はひとつのフィールドを含みます。柔軟に `<ul>` に HTML 属性を指定できるように、`<ul>` や `</ul>` は\*\*含まれません\*\*。

```
>>> f = ContactForm()
>>> f.as_ul()
'<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></li>\n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></li>\n<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></li>\n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></li>'
>>> print(f.as_ul())
<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></li>
<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></li>
<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></li>
<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></li>
```

#### `as_table()`

#### `Form.template_name_table`

The template used by `as_table()`. Default: `'django/forms/table.html'`.

#### `Form.as_table()`

`as_table()` renders the form as an HTML `<table>`:

```
>>> f = ContactForm()
>>> f.as_table()
'<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr>\n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr>\n<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr>'
>>> print(f)
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr>
<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr>
<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr>
```

### 必須フォームとエラーのあるフォームのスタイリング

#### `Form.error_css_class`

#### `Form.required_css_class`

必須フォームやエラーのあるフォームの行を装飾するのはとても一般的です。たとえば、必須フォームの行は太字にしたり、エラーであれば赤色にしたくなることもあるでしょう。

[`Form`](#django.forms.Form) クラスには、必須フォームやエラーのあるフォームに `class` 属性を追加するためのいくつかのフックを用意しています。具体的には、 [`Form.error_css_class`](#django.forms.Form.error_css_class) 属性や [`Form.required_css_class`](#django.forms.Form.required_css_class) 属性をセットします:

```
from django import forms

class ContactForm(forms.Form):
    error_css_class = 'error'
    required_css_class = 'required'

    # ... and the rest of your fields here
```

いったん設定すれば、それらの行は `"error"` クラスや `"required"` クラスが必要に応じて追加されます。HTMLはこのようになるでしょう:

```
>>> f = ContactForm(data)
>>> print(f.as_table())
<tr class="required"><th><label class="required" for="id_subject">Subject:</label>    ...
<tr class="required"><th><label class="required" for="id_message">Message:</label>    ...
<tr class="required error"><th><label class="required" for="id_sender">Sender:</label>      ...
<tr><th><label for="id_cc_myself">Cc myself:<label> ...
>>> f['subject'].label_tag()
<label class="required" for="id_subject">Subject:</label>
>>> f['subject'].legend_tag()
<legend class="required" for="id_subject">Subject:</legend>
>>> f['subject'].label_tag(attrs={'class': 'foo'})
<label for="id_subject" class="foo required">Subject:</label>
>>> f['subject'].legend_tag(attrs={'class': 'foo'})
<legend for="id_subject" class="foo required">Subject:</legend>
```

### フォーム要素の HTML `id` 属性と `<label>` タグを設定する

#### `Form.auto_id`

デフォルトでは、フォームをレンダリングするメソッドは次のものを含みます:

- フォーム要素に対する HTML `id` 属性。
- ラベルの前後に、フォームに対応する `<label>` タグ。 HTML の `<label>` タグは、どのラベルテキストがどのフォーム要素と関係しているかを指定します。この小さな修飾によって、補助的なデバイスでフォームにアクセスするのが便利になります。いつも `<label>` タグを使うようにするとよいでしょう。

`id` 属性の値は、フォームフィールド名に `id_` を前置して生成されます。しかし、もし `id` 規約を変更したかったり、 HTML `id` 属性と `<label>` タグを完全に消し去りたいような場合は、この挙動は変更可能です。

`id` とラベルの挙動を制御するには、 `auto_id` 引数を使います。この引数は、 `True` か `False` か文字列でなければなりません。

`auto_id` が `False` であれば、フォームのアウトプットは `<label>` タグと `id` 属性を含みません:

```
>>> f = ContactForm(auto_id=False)
>>> print(f.as_div())
<div>Subject:<input type="text" name="subject" maxlength="100" required></div>
<div>Message:<textarea name="message" cols="40" rows="10" required></textarea></div>
<div>Sender:<input type="email" name="sender" required></div>
<div>Cc myself:<input type="checkbox" name="cc_myself"></div>
```

`auto_id` が `True` であれば、フォームのアウトプットは `<label>` タグを含み、それぞれのフォームフィールドに対してフィールド名を `id` として使用します。

```
>>> f = ContactForm(auto_id=True)
>>> print(f.as_div())
<div><label for="subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="subject"></div>
<div><label for="message">Message:</label><textarea name="message" cols="40" rows="10" required id="message"></textarea></div>
<div><label for="sender">Sender:</label><input type="email" name="sender" required id="sender"></div>
<div><label for="cc_myself">Cc myself:</label><input type="checkbox" name="cc_myself" id="cc_myself"></div>
```

`auto_id` に、フォーマット指定子 %s を含む文字列が指定されている場合、フォームのアウトプットは `<label>` タグを含み、 `id` 属性をフォーマット文字列に基づいて生成します。たとえば、フォーマット文字列 `'field_%s'` に対して、フィールド名 `subject` は、 `'field_subject'` という `id` の値を得ます。例を続けましょう:

```
>>> f = ContactForm(auto_id='id_for_%s')
>>> print(f.as_div())
<div><label for="id_for_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_for_subject"></div>
<div><label for="id_for_message">Message:</label><textarea name="message" cols="40" rows="10" required id="id_for_message"></textarea></div>
<div><label for="id_for_sender">Sender:</label><input type="email" name="sender" required id="id_for_sender"></div>
<div><label for="id_for_cc_myself">Cc myself:</label><input type="checkbox" name="cc_myself" id="id_for_cc_myself"></div>
```

もし、 `auto_id` がそれ以外の真の値にセットされた場合 -- `%s` を含まない文字列のような -- ライブラリは `auto_id` が `True` の場合と同様に振る舞います。

デフォルトでは、 `auto_id` は文字列 `'id_%s'` がセットされています。

#### `Form.label_suffix`

フォームをレンダリングする際、すべてのラベル名の後ろにつけられる翻訳可能な文字列の接尾語 (英語ではコロン (`:`) がデフォルト) です。

`label_suffix` パラメータを用いて、記号をカスタマイズしたり、完全に削除したりすることが可能です。

```
>>> f = ContactForm(auto_id='id_for_%s', label_suffix='')
>>> print(f.as_div())
<div><label for="id_for_subject">Subject</label><input type="text" name="subject" maxlength="100" required id="id_for_subject"></div>
<div><label for="id_for_message">Message</label><textarea name="message" cols="40" rows="10" required id="id_for_message"></textarea></div>
<div><label for="id_for_sender">Sender</label><input type="email" name="sender" required id="id_for_sender"></div>
<div><label for="id_for_cc_myself">Cc myself</label><input type="checkbox" name="cc_myself" id="id_for_cc_myself"></div>
>>> f = ContactForm(auto_id='id_for_%s', label_suffix=' ->')
>>> print(f.as_div())
<div><label for="id_for_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_for_subject"></div>
<div><label for="id_for_message">Message -&gt;</label><textarea name="message" cols="40" rows="10" required id="id_for_message"></textarea></div>
<div><label for="id_for_sender">Sender -&gt;</label><input type="email" name="sender" required id="id_for_sender"></div>
<div><label for="id_for_cc_myself">Cc myself -&gt;</label><input type="checkbox" name="cc_myself" id="id_for_cc_myself"></div>
```

接尾文字列は、ラベルの最後の文字が句読文字 (英語では、 `.`, `!`, `?`, `:`) でない場合に限ってつけられます。

Fields can also define their own [`label_suffix`](/ja/4.1/ref/forms/fields/#django.forms.Field.label_suffix).
This will take precedence over [`Form.label_suffix`](#django.forms.Form.label_suffix). The suffix can also be overridden at runtime
using the `label_suffix` parameter to
[`label_tag()`](#django.forms.BoundField.label_tag)/
[`legend_tag()`](#django.forms.BoundField.legend_tag).

#### `Form.use_required_attribute`

`True` (デフォルト値) に設定した場合、必須フォームフィールドは HTMLの `required` 属性を伴います。

[Formsets](/ja/4.1/topics/forms/formsets/) は、フォームセットにフォームを追加または削除したときのブラウザの誤検証を避けるため、 `use_required_attribute=False` としてフォームをインスタンス化します。

### フォームウィジェットのレンダリングを設定する

#### `Form.default_renderer`

フォームの [renderer](/ja/4.1/ref/forms/renderers/) を指定します。デフォルトは `None` で、 [`FORM_RENDERER`](/ja/4.1/ref/settings/#std-setting-FORM_RENDERER) 設定で指定されたデフォルトのレンダラーを使用することを意味します。

これはクラスの属性としてフォーム定義の際に設定するもしくは、`Form.__init__()` に `renderer` 引数を使うことで設定します。たとえば:

```
from django import forms

class MyForm(forms.Form):
    default_renderer = MyRenderer()
```

もしくは:

```
form = MyForm(renderer=MyRenderer())
```

### フィールドの順序に関する記述

`as_p()`, `as_ul()`,  `as_table()` ショートカットでは、フィールドはフォームクラスで定義した順序で表示されます。たとえば、 `ContactForm` の例では、フィールドは `subject`, `message`, `sender`, `cc_myself` の順で定義されます。 HTML アウトプットの順序を変更するには、クラスの中で定義する順序を変えます。

順序のカスタマイズには、ほかにもいくつかの方法があります:

#### `Form.field_order`

By default `Form.field_order=None`, which retains the order in which you
define the fields in your form class. If `field_order` is a list of field
names, the fields are ordered as specified by the list and remaining fields are
appended according to the default order. Unknown field names in the list are
ignored. This makes it possible to disable a field in a subclass by setting it
to `None` without having to redefine ordering.

[`Form`](#django.forms.Form) に `Form.field_order` 引数を使うことで、フィールドの順序をオーバーライドすることもできます。 [`Form`](#django.forms.Form) の中で [`field_order`](#django.forms.Form.field_order) が定義されていて、 *かつ* `Form` をインスタンス化する際に `field_order` をインクルードする場合、後者の `field_order` が優先されます。

#### `Form.order_fields(field_order)`

また、 `order_fields()` に [`field_order`](#django.forms.Form.field_order) と同様のフィールド名のリストを用いて、いつでもフィールドの順序を変更することができます。

### エラーの表示方法

bound な `Form` オブジェクトをレンダリングしたとき、フォームの検証がまだ行われていない場合は自動的に検証が行われ、 HTML アウトプットの該当フィールドの近くに検証エラーが `<ul class="errorlist">` として含まれます。個別のエラーメッセージの表示位置は、使用されているアウトプットメソッドに依存します:

```
>>> data = {'subject': '',
...         'message': 'Hi there',
...         'sender': 'invalid email address',
...         'cc_myself': True}
>>> f = ContactForm(data, auto_id=False)
>>> print(f.as_div())
<div>Subject:<ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" required></div>
<div>Message:<textarea name="message" cols="40" rows="10" required>Hi there</textarea></div>
<div>Sender:<ul class="errorlist"><li>Enter a valid email address.</li></ul><input type="email" name="sender" value="invalid email address" required></div>
<div>Cc myself:<input type="checkbox" name="cc_myself" checked></div>
>>> print(f.as_table())
<tr><th>Subject:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" required></td></tr>
<tr><th>Message:</th><td><textarea name="message" cols="40" rows="10" required></textarea></td></tr>
<tr><th>Sender:</th><td><ul class="errorlist"><li>Enter a valid email address.</li></ul><input type="email" name="sender" value="invalid email address" required></td></tr>
<tr><th>Cc myself:</th><td><input checked type="checkbox" name="cc_myself"></td></tr>
>>> print(f.as_ul())
<li><ul class="errorlist"><li>This field is required.</li></ul>Subject: <input type="text" name="subject" maxlength="100" required></li>
<li>Message: <textarea name="message" cols="40" rows="10" required></textarea></li>
<li><ul class="errorlist"><li>Enter a valid email address.</li></ul>Sender: <input type="email" name="sender" value="invalid email address" required></li>
<li>Cc myself: <input checked type="checkbox" name="cc_myself"></li>
>>> print(f.as_p())
<p><ul class="errorlist"><li>This field is required.</li></ul></p>
<p>Subject: <input type="text" name="subject" maxlength="100" required></p>
<p>Message: <textarea name="message" cols="40" rows="10" required></textarea></p>
<p><ul class="errorlist"><li>Enter a valid email address.</li></ul></p>
<p>Sender: <input type="email" name="sender" value="invalid email address" required></p>
<p>Cc myself: <input checked type="checkbox" name="cc_myself"></p>
```

### エラーリストのフォーマットをカスタムする

#### `class ErrorList(initlist=None, error_class=None, renderer=None)`

By default, forms use `django.forms.utils.ErrorList` to format validation
errors. `ErrorList` is a list like object where `initlist` is the
list of errors. In addition this class has the following attributes and
methods.

#### `error_class`

The CSS classes to be used when rendering the error list. Any provided
classes are added to the default `errorlist` class.

#### `renderer`

> **New in Django 4.0**

Specifies the [renderer](/ja/4.1/ref/forms/renderers/) to use for `ErrorList`.
Defaults to `None` which means to use the default renderer
specified by the [`FORM_RENDERER`](/ja/4.1/ref/settings/#std-setting-FORM_RENDERER) setting.

#### `template_name`

> **New in Django 4.0**

The name of the template used when calling `__str__` or
[`render()`](#django.forms.ErrorList.render). By default this is
`'django/forms/errors/list/default.html'` which is a proxy for the
`'ul.html'` template.

#### `template_name_text`

> **New in Django 4.0**

The name of the template used when calling [`as_text()`](#django.forms.ErrorList.as_text). By default
this is `'django/forms/errors/list/text.html'`. This template renders
the errors as a list of bullet points.

#### `template_name_ul`

> **New in Django 4.0**

The name of the template used when calling [`as_ul()`](#django.forms.ErrorList.as_ul). By default
this is `'django/forms/errors/list/ul.html'`. This template renders
the errors in `<li>` tags with a wrapping `<ul>` with the CSS
classes as defined by [`error_class`](#django.forms.ErrorList.error_class).

#### `get_context()`

> **New in Django 4.0**

Return context for rendering of errors in a template.

The available context is:

- `errors` : A list of the errors.
- `error_class` : A string of CSS classes.

#### `render(template_name=None, context=None, renderer=None)`

> **New in Django 4.0**

The render method is called by `__str__` as well as by the
[`as_ul()`](#django.forms.ErrorList.as_ul) method.

All arguments are optional and will default to:

- `template_name`: Value returned by [`template_name`](#django.forms.ErrorList.template_name)
- `context`: Value returned by [`get_context()`](#django.forms.ErrorList.get_context)
- `renderer`: Value returned by [`renderer`](#django.forms.ErrorList.renderer)

#### `as_text()`

Renders the error list using the template defined by
[`template_name_text`](#django.forms.ErrorList.template_name_text).

#### `as_ul()`

Renders the error list using the template defined by
[`template_name_ul`](#django.forms.ErrorList.template_name_ul).

If you'd like to customize the rendering of errors this can be achieved by
overriding the [`template_name`](#django.forms.ErrorList.template_name) attribute or more generally by
overriding the default template, see also
[Overriding built-in form templates](/ja/4.1/ref/forms/renderers/#overriding-built-in-form-templates).

> **Changed in Django 4.0**
>
> Rendering of [`ErrorList`](#django.forms.ErrorList) was moved to the template engine.

> **Deprecated since Django 4.0**
>
> バージョン 4.0 で非推奨: The ability to return a `str` when calling the `__str__` method is
> deprecated. Use the template engine instead which returns a `SafeString`.

## さらに詳細なアウトプット

`as_p()`, `as_ul()`, `as_table()` メソッドはショートカットです -- フォームオブジェクトを表示する唯一の方法ではありません。

#### `class BoundField`

[`Form`](#django.forms.Form) インスタンスのひとつのフィールドを HTML として表示したり、その属性にアクセスするのに使います。

このオブジェクトの `__str__()` メソッドは、このフィールドの HTML を表示します。

ひとつの `BoundField` を引き出すには、フォームにフィールド名をキーとしたディクショナリルックアップ構文を使います:

```
>>> form = ContactForm()
>>> print(form['subject'])
<input id="id_subject" type="text" name="subject" maxlength="100" required>
```

すべての `BoundField` オブジェクトを引き出すには、フォームを iterate します:

```
>>> form = ContactForm()
>>> for boundfield in form: print(boundfield)
<input id="id_subject" type="text" name="subject" maxlength="100" required>
<input type="text" name="message" id="id_message" required>
<input type="email" name="sender" id="id_sender" required>
<input type="checkbox" name="cc_myself" id="id_cc_myself">
```

フィールドごとのアウトプットは、フォームオブジェクトの `auto_id` 設定を受け取ります:

```
>>> f = ContactForm(auto_id=False)
>>> print(f['message'])
<input type="text" name="message" required>
>>> f = ContactForm(auto_id='id_%s')
>>> print(f['message'])
<input type="text" name="message" id="id_message" required>
```

### `BoundField` の属性一覧

#### `BoundField.auto_id`

この `BoundField` の HTML ID 属性。 [`Form.auto_id`](#django.forms.Form.auto_id) が `False` であれば、空の文字列を返します。

#### `BoundField.data`

このプロパティは、ウィジェットの [`value_from_datadict()`](/ja/4.1/ref/forms/widgets/#django.forms.Widget.value_from_datadict) メソッドをによって抽出された [`BoundField`](#django.forms.BoundField) のデータを返し、データが無い場合は `None` を返します:

```
>>> unbound_form = ContactForm()
>>> print(unbound_form['subject'].data)
None
>>> bound_form = ContactForm(data={'subject': 'My Subject'})
>>> print(bound_form['subject'].data)
My Subject
```

#### `BoundField.errors`

`print` された際、 HTML で `<ul class="errorlist">` として表示される [list-like object](#ref-forms-error-list-format) です。

```
>>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''}
>>> f = ContactForm(data, auto_id=False)
>>> print(f['message'])
<input type="text" name="message" required>
>>> f['message'].errors
['This field is required.']
>>> print(f['message'].errors)
<ul class="errorlist"><li>This field is required.</li></ul>
>>> f['subject'].errors
[]
>>> print(f['subject'].errors)

>>> str(f['subject'].errors)
''
```

#### `BoundField.field`

この [`BoundField`](#django.forms.BoundField) がラップしているフォームクラスの [`Field`](/ja/4.1/ref/forms/fields/#django.forms.Field) インスタンス。

#### `BoundField.form`

この [`BoundField`](#django.forms.BoundField) がくくりつけられている [`Form`](#django.forms.Form) インスタンス。

#### `BoundField.help_text`

フィールドの [`help_text`](/ja/4.1/ref/forms/fields/#django.forms.Field.help_text) 。

#### `BoundField.html_name`

The name that will be used in the widget's HTML `name` attribute. It takes
the form [`prefix`](#django.forms.Form.prefix) into account.

#### `BoundField.id_for_label`

Use this property to render the ID of this field. For example, if you are
manually constructing a `<label>` in your template (despite the fact that
[`label_tag()`](#django.forms.BoundField.label_tag)/[`legend_tag()`](#django.forms.BoundField.legend_tag) will do this
for you):

```html+django
<label for="{{ form.my_field.id_for_label }}">...</label>{{ my_field }}
```

By default, this will be the field's name prefixed by `id_`
("`id_my_field`" for the example above). You may modify the ID by setting
[`attrs`](/ja/4.1/ref/forms/widgets/#django.forms.Widget.attrs) on the field's widget. For example,
declaring a field like this:

```
my_field = forms.CharField(widget=forms.TextInput(attrs={'id': 'myFIELD'}))
```

and using the template above, would render something like:

```html
<label for="myFIELD">...</label><input id="myFIELD" type="text" name="my_field" required>
```

#### `BoundField.initial`

Use [`BoundField.initial`](#django.forms.BoundField.initial) to retrieve initial data for a form field.
It retrieves the data from [`Form.initial`](#django.forms.Form.initial) if present, otherwise
trying [`Field.initial`](/ja/4.1/ref/forms/fields/#django.forms.Field.initial). Callable values are evaluated. See
[Initial form values](#ref-forms-initial-form-values) for more examples.

[`BoundField.initial`](#django.forms.BoundField.initial) caches its return value, which is useful
especially when dealing with callables whose return values can change (e.g.
`datetime.now` or `uuid.uuid4`):

```
>>> from datetime import datetime
>>> class DatedCommentForm(CommentForm):
...     created = forms.DateTimeField(initial=datetime.now)
>>> f = DatedCommentForm()
>>> f['created'].initial
datetime.datetime(2021, 7, 27, 9, 5, 54)
>>> f['created'].initial
datetime.datetime(2021, 7, 27, 9, 5, 54)
```

Using [`BoundField.initial`](#django.forms.BoundField.initial) is recommended over
[`get_initial_for_field()`](#django.forms.Form.get_initial_for_field).

#### `BoundField.is_hidden`

Returns `True` if this [`BoundField`](#django.forms.BoundField)'s widget is
hidden.

#### `BoundField.label`

The [`label`](/ja/4.1/ref/forms/fields/#django.forms.Field.label) of the field. This is used in
[`label_tag()`](#django.forms.BoundField.label_tag)/[`legend_tag()`](#django.forms.BoundField.legend_tag).

#### `BoundField.name`

The name of this field in the form:

```
>>> f = ContactForm()
>>> print(f['subject'].name)
subject
>>> print(f['message'].name)
message
```

#### `BoundField.use_fieldset`

> **New in Django 4.1**

Returns the value of this BoundField widget's `use_fieldset` attribute.

#### `BoundField.widget_type`

Returns the lowercased class name of the wrapped field's widget, with any
trailing `input` or `widget` removed. This may be used when building
forms where the layout is dependent upon the widget type. For example:

```
{% for field in form %}
    {% if field.widget_type == 'checkbox' %}
        # render one way
    {% else %}
        # render another way
    {% endif %}
{% endfor %}
```

### Methods of `BoundField`

#### `BoundField.as_hidden(attrs=None, **kwargs)`

Returns a string of HTML for representing this as an `<input type="hidden">`.

`**kwargs` are passed to [`as_widget()`](#django.forms.BoundField.as_widget).

This method is primarily used internally. You should use a widget instead.

#### `BoundField.as_widget(widget=None, attrs=None, only_initial=False)`

Renders the field by rendering the passed widget, adding any HTML
attributes passed as `attrs`.  If no widget is specified, then the
field's default widget will be used.

`only_initial` is used by Django internals and should not be set
explicitly.

#### `BoundField.css_classes(extra_classes=None)`

When you use Django's rendering shortcuts, CSS classes are used to
indicate required form fields or fields that contain errors. If you're
manually rendering a form, you can access these CSS classes using the
`css_classes` method:

```
>>> f = ContactForm(data={'message': ''})
>>> f['message'].css_classes()
'required'
```

If you want to provide some additional classes in addition to the
error and required classes that may be required, you can provide
those classes as an argument:

```
>>> f = ContactForm(data={'message': ''})
>>> f['message'].css_classes('foo bar')
'foo bar required'
```

#### `BoundField.label_tag(contents=None, attrs=None, label_suffix=None, tag=None)`

Renders a label tag for the form field using the template specified by
[`Form.template_name_label`](#django.forms.Form.template_name_label).

The available context is:

- `field`: This instance of the [`BoundField`](#django.forms.BoundField).
- `contents`: By default a concatenated string of
  [`BoundField.label`](#django.forms.BoundField.label) and [`Form.label_suffix`](#django.forms.Form.label_suffix) (or
  [`Field.label_suffix`](/ja/4.1/ref/forms/fields/#django.forms.Field.label_suffix), if set). This can be overridden by the
  `contents` and `label_suffix` arguments.
- `attrs`: A `dict` containing `for`,
  [`Form.required_css_class`](#django.forms.Form.required_css_class), and `id`. `id` is generated by the
  field's widget `attrs` or [`BoundField.auto_id`](#django.forms.BoundField.auto_id). Additional
  attributes can be provided by the `attrs` argument.
- `use_tag`: A boolean which is `True` if the label has an `id`.
  If `False` the default template omits the `tag`.
- `tag`: An optional string to customize the tag, defaults to `label`.

> **Tip**
>
> In your template `field` is the instance of the `BoundField`.
> Therefore `field.field` accesses [`BoundField.field`](#django.forms.BoundField.field) being
> the field you declare, e.g. `forms.CharField`.

To separately render the label tag of a form field, you can call its
`label_tag()` method:

```
>>> f = ContactForm(data={'message': ''})
>>> print(f['message'].label_tag())
<label for="id_message">Message:</label>
```

If you'd like to customize the rendering this can be achieved by overriding
the [`Form.template_name_label`](#django.forms.Form.template_name_label) attribute or more generally by
overriding the default template, see also
[Overriding built-in form templates](/ja/4.1/ref/forms/renderers/#overriding-built-in-form-templates).

> **Changed in Django 4.0**
>
> The label is now rendered using the template engine.

> **Changed in Django 4.1**
>
> The `tag` argument was added.

#### `BoundField.legend_tag(contents=None, attrs=None, label_suffix=None)`

> **New in Django 4.1**

Calls [`label_tag()`](#django.forms.BoundField.label_tag) with `tag='legend'` to render the label with
`<legend>` tags. This is useful when rendering radio and multiple
checkbox widgets where `<legend>` may be more appropriate than a
`<label>`.

#### `BoundField.value()`

Use this method to render the raw value of this field as it would be rendered
by a `Widget`:

```
>>> initial = {'subject': 'welcome'}
>>> unbound_form = ContactForm(initial=initial)
>>> bound_form = ContactForm(data={'subject': 'hi'}, initial=initial)
>>> print(unbound_form['subject'].value())
welcome
>>> print(bound_form['subject'].value())
hi
```

## Customizing `BoundField`

If you need to access some additional information about a form field in a
template and using a subclass of [`Field`](/ja/4.1/ref/forms/fields/#django.forms.Field) isn't
sufficient, consider also customizing [`BoundField`](#django.forms.BoundField).

A custom form field can override `get_bound_field()`:

#### `Field.get_bound_field(form, field_name)`

Takes an instance of [`Form`](#django.forms.Form) and the name of the field.
The return value will be used when accessing the field in a template. Most
likely it will be an instance of a subclass of
[`BoundField`](#django.forms.BoundField).

If you have a `GPSCoordinatesField`, for example, and want to be able to
access additional information about the coordinates in a template, this could
be implemented as follows:

```
class GPSCoordinatesBoundField(BoundField):
    @property
    def country(self):
        """
        Return the country the coordinates lie in or None if it can't be
        determined.
        """
        value = self.value()
        if value:
            return get_country_from_coordinates(value)
        else:
            return None

class GPSCoordinatesField(Field):
    def get_bound_field(self, form, field_name):
        return GPSCoordinatesBoundField(form, self, field_name)
```

Now you can access the country in a template with
`{{ form.coordinates.country }}`.

## Binding uploaded files to a form

Dealing with forms that have `FileField` and `ImageField` fields
is a little more complicated than a normal form.

Firstly, in order to upload files, you'll need to make sure that your
`<form>` element correctly defines the `enctype` as
`"multipart/form-data"`:

```
<form enctype="multipart/form-data" method="post" action="/foo/">
```

Secondly, when you use the form, you need to bind the file data. File
data is handled separately to normal form data, so when your form
contains a `FileField` and `ImageField`, you will need to specify
a second argument when you bind your form. So if we extend our
ContactForm to include an `ImageField` called `mugshot`, we
need to bind the file data containing the mugshot image:

```
# Bound form with an image field
>>> from django.core.files.uploadedfile import SimpleUploadedFile
>>> data = {'subject': 'hello',
...         'message': 'Hi there',
...         'sender': 'foo@example.com',
...         'cc_myself': True}
>>> file_data = {'mugshot': SimpleUploadedFile('face.jpg', <file data>)}
>>> f = ContactFormWithMugshot(data, file_data)
```

In practice, you will usually specify `request.FILES` as the source
of file data (just like you use `request.POST` as the source of
form data):

```
# Bound form with an image field, data from the request
>>> f = ContactFormWithMugshot(request.POST, request.FILES)
```

Constructing an unbound form is the same as always -- omit both form data *and*
file data:

```
# Unbound form with an image field
>>> f = ContactFormWithMugshot()
```

### Testing for multipart forms

#### `Form.is_multipart()`

If you're writing reusable views or templates, you may not know ahead of time
whether your form is a multipart form or not. The `is_multipart()` method
tells you whether the form requires multipart encoding for submission:

```
>>> f = ContactFormWithMugshot()
>>> f.is_multipart()
True
```

Here's an example of how you might use this in a template:

```
{% if form.is_multipart %}
    <form enctype="multipart/form-data" method="post" action="/foo/">
{% else %}
    <form method="post" action="/foo/">
{% endif %}
{{ form }}
</form>
```

## Subclassing forms

If you have multiple `Form` classes that share fields, you can use
subclassing to remove redundancy.

When you subclass a custom `Form` class, the resulting subclass will
include all fields of the parent class(es), followed by the fields you define
in the subclass.

In this example, `ContactFormWithPriority` contains all the fields from
`ContactForm`, plus an additional field, `priority`. The `ContactForm`
fields are ordered first:

```
>>> class ContactFormWithPriority(ContactForm):
...     priority = forms.CharField()
>>> f = ContactFormWithPriority(auto_id=False)
>>> print(f.as_div())
<div>Subject:<input type="text" name="subject" maxlength="100" required></div>
<div>Message:<textarea name="message" cols="40" rows="10" required></textarea></div>
<div>Sender:<input type="email" name="sender" required></div>
<div>Cc myself:<input type="checkbox" name="cc_myself"></div>
<div>Priority:<input type="text" name="priority" required></div>
```

It's possible to subclass multiple forms, treating forms as mixins. In this
example, `BeatleForm` subclasses both `PersonForm` and `InstrumentForm`
(in that order), and its field list includes the fields from the parent
classes:

```
>>> from django import forms
>>> class PersonForm(forms.Form):
...     first_name = forms.CharField()
...     last_name = forms.CharField()
>>> class InstrumentForm(forms.Form):
...     instrument = forms.CharField()
>>> class BeatleForm(InstrumentForm, PersonForm):
...     haircut_type = forms.CharField()
>>> b = BeatleForm(auto_id=False)
>>> print(b.as_div())
<div>First name:<input type="text" name="first_name" required></div>
<div>Last name:<input type="text" name="last_name" required></div>
<div>Instrument:<input type="text" name="instrument" required></div>
<div>Haircut type:<input type="text" name="haircut_type" required></div>
```

It's possible to declaratively remove a `Field` inherited from a parent class
by setting the name of the field to `None` on the subclass. For example:

```
>>> from django import forms

>>> class ParentForm(forms.Form):
...     name = forms.CharField()
...     age = forms.IntegerField()

>>> class ChildForm(ParentForm):
...     name = None

>>> list(ChildForm().fields)
['age']
```

## Prefixes for forms

#### `Form.prefix`

You can put several Django forms inside one `<form>` tag. To give each
`Form` its own namespace, use the `prefix` keyword argument:

```
>>> mother = PersonForm(prefix="mother")
>>> father = PersonForm(prefix="father")
>>> print(mother.as_div())
<div><label for="id_mother-first_name">First name:</label><input type="text" name="mother-first_name" required id="id_mother-first_name"></div>
<div><label for="id_mother-last_name">Last name:</label><input type="text" name="mother-last_name" required id="id_mother-last_name"></div>
>>> print(father.as_div())
<div><label for="id_father-first_name">First name:</label><input type="text" name="father-first_name" required id="id_father-first_name"></div>
<div><label for="id_father-last_name">Last name:</label><input type="text" name="father-last_name" required id="id_father-last_name"></div>
```

The prefix can also be specified on the form class:

```
>>> class PersonForm(forms.Form):
...     ...
...     prefix = 'person'
```
