Form fieldsLink to this heading
- class Field(**kwargs)Link to this definition
Form クラスを作成時の一番重要な部分は、form のフィールド (field) の定義です。各フィールドにはカスタムの検証ロジックがあり、他にいくつかのフックもあります。
- Field.clean(value)Link to this definition
Field クラスは主に Form クラス内で使われますが、インスタンスを作って直接使ったほうが便利に使えることもあります。各 Field インスタンスは1つの引数をとる clean() メソッドを持っており、次の例に示すように、django.forms.ValidationError 例外を発生したり、クリーンな値を返してくれます。
>>> from django import forms
>>> f = forms.EmailField()
>>> f.clean('foo@example.com')
'foo@example.com'
>>> f.clean('invalid email address')
Traceback (most recent call last):
...
ValidationError: ['Enter a valid email address.']
field のコアとなる引数Link to this heading
各 Field クラスのコンストラクタは少なくとも以下の引数を受け付けます。Field クラスによっては追加のフィールド固有の引数も取れることがありますが、以下に説明する引数は 常に 取ることができます。
requiredLink to this heading
- Field.requiredLink to this definition
By default, each Field class assumes the value is required, so if you pass
an empty value -- either None or the empty string ("") -- then
clean() will raise a ValidationError exception:
>>> from django import forms
>>> f = forms.CharField()
>>> f.clean('foo')
'foo'
>>> f.clean('')
Traceback (most recent call last):
...
ValidationError: ['This field is required.']
>>> f.clean(None)
Traceback (most recent call last):
...
ValidationError: ['This field is required.']
>>> f.clean(' ')
' '
>>> f.clean(0)
'0'
>>> f.clean(True)
'True'
>>> f.clean(False)
'False'
To specify that a field is not required, pass required=False to the
Field constructor:
>>> f = forms.CharField(required=False)
>>> f.clean('foo')
'foo'
>>> f.clean('')
''
>>> f.clean(None)
''
>>> f.clean(0)
'0'
>>> f.clean(True)
'True'
>>> f.clean(False)
'False'
If a Field has required=False and you pass clean() an empty value,
then clean() will return a normalized empty value rather than raising
ValidationError. For CharField, this will be an empty string. For other
Field classes, it might be None. (This varies from field to field.)
Widgets of required form fields have the required HTML attribute. Set the
Form.use_required_attribute attribute to False to disable it. The
required attribute isn't included on forms of formsets because the browser
validation may not be correct when adding and deleting formsets.
labelLink to this heading
- Field.labelLink to this definition
label 属性は、フィールドに対する "人が読みやすい" ラベルを指定します。このラベルは Field が Form 内で表示されるときに使用されます。
上述の "HTML としてフォームを出力する" で説明したとおり、Field に対するデフォルトのラベルはアンダースコアを空白に、また単語の最初の小文字を大文字に変換して生成されます。 デフォルトではない文字列を表示したい場合には、label を指定してください。
以下は、label を 2 つのフィールドに実装した Form の実例です。出力を見やすくするため auto_id=False を指定しています。
>>> from django import forms
>>> class CommentForm(forms.Form):
... name = forms.CharField(label='Your name')
... url = forms.URLField(label='Your website', required=False)
... comment = forms.CharField()
>>> f = CommentForm(auto_id=False)
>>> print(f)
<tr><th>Your name:</th><td><input type="text" name="name" required></td></tr>
<tr><th>Your website:</th><td><input type="url" name="url"></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" required></td></tr>
label_suffixLink to this heading
- Field.label_suffixLink to this definition
label_suffix 属性は、フィールドごとの label_suffix をオーバーライドします:
>>> class ContactForm(forms.Form):
... age = forms.IntegerField()
... nationality = forms.CharField()
... captcha_answer = forms.IntegerField(label='2 + 2', label_suffix=' =')
>>> f = ContactForm(label_suffix='?')
>>> print(f.as_p())
<p><label for="id_age">Age?</label> <input id="id_age" name="age" type="number" required></p>
<p><label for="id_nationality">Nationality?</label> <input id="id_nationality" name="nationality" type="text" required></p>
<p><label for="id_captcha_answer">2 + 2 =</label> <input id="id_captcha_answer" name="captcha_answer" type="number" required></p>
initialLink to this heading
- Field.initialLink to this definition
initial 属性は、Field が結びつけられていない Form で表示されるときに使われる初期値を指定します。
動的に初期値を指定する方法は、Form.initial パラメータを参照してください。
The use-case for this is when you want to display an "empty" form in which a field is initialized to a particular value. For example:
>>> from django import forms
>>> class CommentForm(forms.Form):
... name = forms.CharField(initial='Your name')
... url = forms.URLField(initial='http://')
... comment = forms.CharField()
>>> f = CommentForm(auto_id=False)
>>> print(f)
<tr><th>Name:</th><td><input type="text" name="name" value="Your name" required></td></tr>
<tr><th>Url:</th><td><input type="url" name="url" value="http://" required></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" required></td></tr>
You may be thinking, why not just pass a dictionary of the initial values as data when displaying the form? Well, if you do that, you'll trigger validation, and the HTML output will include any validation errors:
>>> class CommentForm(forms.Form):
... name = forms.CharField()
... url = forms.URLField()
... comment = forms.CharField()
>>> default_data = {'name': 'Your name', 'url': 'http://'}
>>> f = CommentForm(default_data, auto_id=False)
>>> print(f)
<tr><th>Name:</th><td><input type="text" name="name" value="Your name" required></td></tr>
<tr><th>Url:</th><td><ul class="errorlist"><li>Enter a valid URL.</li></ul><input type="url" name="url" value="http://" required></td></tr>
<tr><th>Comment:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="comment" required></td></tr>
This is why initial values are only displayed for unbound forms. For bound
forms, the HTML output will use the bound data.
Also note that initial values are not used as "fallback" data in
validation if a particular field's value is not given. initial values are
only intended for initial form display:
>>> class CommentForm(forms.Form):
... name = forms.CharField(initial='Your name')
... url = forms.URLField(initial='http://')
... comment = forms.CharField()
>>> data = {'name': '', 'url': '', 'comment': 'Foo'}
>>> f = CommentForm(data)
>>> f.is_valid()
False
# The form does *not* fall back to using the initial values.
>>> f.errors
{'url': ['This field is required.'], 'name': ['This field is required.']}
Instead of a constant, you can also pass any callable:
>>> import datetime
>>> class DateForm(forms.Form):
... day = forms.DateField(initial=datetime.date.today)
>>> print(DateForm())
<tr><th>Day:</th><td><input type="text" name="day" value="12/23/2008" required><td></tr>
The callable will be evaluated only when the unbound form is displayed, not when it is defined.
widgetLink to this heading
- Field.widgetLink to this definition
widget 引数は、Field をレンダリングするときに使う Widget クラスを指定します。詳しくは ウィジェット を参照してください。
help_textLink to this heading
- Field.help_textLink to this definition
help_text 引数は、Field を説明するテキストを指定します。help_text を指定した場合、容易な Form メソッド (例えば as_ul()) で Field がレンダリングされるときに、Field の隣に表示されます。
モデルフィールドの help_text と同じく、値は自動的に生成されるフォーム内で HTML 用にエスケープされません。
Here's a full example Form that implements help_text for two of its
fields. We've specified auto_id=False to simplify the output:
>>> from django import forms
>>> class HelpTextContactForm(forms.Form):
... subject = forms.CharField(max_length=100, help_text='100 characters max.')
... message = forms.CharField()
... sender = forms.EmailField(help_text='A valid email address, please.')
... cc_myself = forms.BooleanField(required=False)
>>> f = HelpTextContactForm(auto_id=False)
>>> print(f.as_table())
<tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" required><br><span class="helptext">100 characters max.</span></td></tr>
<tr><th>Message:</th><td><input type="text" name="message" required></td></tr>
<tr><th>Sender:</th><td><input type="email" name="sender" required><br>A valid email address, please.</td></tr>
<tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself"></td></tr>
>>> print(f.as_ul()))
<li>Subject: <input type="text" name="subject" maxlength="100" required> <span class="helptext">100 characters max.</span></li>
<li>Message: <input type="text" name="message" required></li>
<li>Sender: <input type="email" name="sender" required> A valid email address, please.</li>
<li>Cc myself: <input type="checkbox" name="cc_myself"></li>
>>> print(f.as_p())
<p>Subject: <input type="text" name="subject" maxlength="100" required> <span class="helptext">100 characters max.</span></p>
<p>Message: <input type="text" name="message" required></p>
<p>Sender: <input type="email" name="sender" required> A valid email address, please.</p>
<p>Cc myself: <input type="checkbox" name="cc_myself"></p>
error_messagesLink to this heading
- Field.error_messagesLink to this definition
The error_messages argument lets you override the default messages that the
field will raise. Pass in a dictionary with keys matching the error messages you
want to override. For example, here is the default error message:
>>> from django import forms
>>> generic = forms.CharField()
>>> generic.clean('')
Traceback (most recent call last):
...
ValidationError: ['This field is required.']
And here is a custom error message:
>>> name = forms.CharField(error_messages={'required': 'Please enter your name'})
>>> name.clean('')
Traceback (most recent call last):
...
ValidationError: ['Please enter your name']
In the built-in Field classes section below, each Field defines the
error message keys it uses.
validatorsLink to this heading
- Field.validatorsLink to this definition
validators 引数は、フィールドに対するバリデーション関数のリストを指定します。
詳しくは validators documentation を参照してください。
localizeLink to this heading
- Field.localizeLink to this definition
localize 引数は、form データの入力とレンダリングした出力のローカライゼーションを有効にします。
詳しくは 書式のローカライゼーション ドキュメントを読んでください。
disabledLink to this heading
- Field.disabledLink to this definition
disabled はブール値の引数を取ります。 True にセットされた場合、フォームのフィールドを disabled HTML 属性を使って無効化し、ユーザーが編集できないようにします。たとえユーザーが勝手にフィールドの値を書き換えてサーバーに送信したとしても、フォームの初期データを使い、書き換えられたデータは無視します。
フィールドのデータの変更チェックLink to this heading
has_changed()Link to this heading
- Field.has_changed()Link to this definition
has_changed() メソッドは、フィールドの値が最初の値から変更されたかどうかを確認するのに使用します。True または False を返します。
詳しくは Form.has_changed() ドキュメントを読んでください。
ビルトインの Field クラスLink to this heading
Naturally, the forms library comes with a set of Field classes that
represent common validation needs. This section documents each built-in field.
For each field, we describe the default widget used if you don't specify
widget. We also specify the value returned when you provide an empty value
(see the section on required above to understand what that means).
BooleanFieldLink to this heading
- class BooleanField(**kwargs)Link to this definition
デフォルトのウィジェット:
CheckboxInput空の値:
FalseNormalizes to: A Python
TrueorFalsevalue.Validates that the value is
True(e.g. the check box is checked) if the field hasrequired=True.Error message keys:
required
CharFieldLink to this heading
- class CharField(**kwargs)Link to this definition
デフォルトのウィジェット:
TextInput空の値:
empty_valueとして与えたものNormalizes to: A string.
Uses
MaxLengthValidatorandMinLengthValidatorifmax_lengthandmin_lengthare provided. Otherwise, all inputs are valid.Error message keys:
required,max_length,min_length
Has three optional arguments for validation:
- max_lengthLink to this definition
- min_lengthLink to this definition
If provided, these arguments ensure that the string is at most or at least the given length.
- stripLink to this definition
If
True(default), the value will be stripped of leading and trailing whitespace.
- empty_valueLink to this definition
The value to use to represent "empty". Defaults to an empty string.
ChoiceFieldLink to this heading
- class ChoiceField(**kwargs)Link to this definition
デフォルトのウィジェット:
Select空の値:
''(空の文字列)Normalizes to: A string.
Validates that the given value exists in the list of choices.
Error message keys:
required,invalid_choice
The
invalid_choiceerror message may contain%(value)s, which will be replaced with the selected choice.Takes one extra argument:
- choicesLink to this definition
Either an iterable of 2-tuples to use as choices for this field, or a callable that returns such an iterable. This argument accepts the same formats as the
choicesargument to a model field. See the model field reference documentation on choices for more details. If the argument is a callable, it is evaluated each time the field's form is initialized. Defaults to an empty list.
TypedChoiceFieldLink to this heading
- class TypedChoiceField(**kwargs)Link to this definition
Just like a
ChoiceField, exceptTypedChoiceFieldtakes two extra arguments,coerceandempty_value.デフォルトのウィジェット:
Select空の値:
empty_valueとして与えたものNormalizes to: A value of the type provided by the
coerceargument.Validates that the given value exists in the list of choices and can be coerced.
Error message keys:
required,invalid_choice
Takes extra arguments:
- coerceLink to this definition
A function that takes one argument and returns a coerced value. Examples include the built-in
int,float,booland other types. Defaults to an identity function. Note that coercion happens after input validation, so it is possible to coerce to a value not present inchoices.
- empty_valueLink to this definition
The value to use to represent "empty." Defaults to the empty string;
Noneis another common choice here. Note that this value will not be coerced by the function given in thecoerceargument, so choose it accordingly.
DateFieldLink to this heading
- class DateField(**kwargs)Link to this definition
デフォルトのウィジェット:
DateInput空の値:
NonePython の
datetime.dateオブジェクトに正規化されます。与えられた値が
datetime.date、datetime.datetimeまたは特定の日付の表示形式のどれかに当てはまるか検証します。エラーメッセージのキー:
required、invalid
1 つの省略可能な引数を取ります:
- input_formatsLink to this definition
文字列を有効な
datetime.dateオブジェクトに変換する試行に使う表示形式のリストです。
input_formats引数が指定されなかった場合、デフォルトのインプット表示形式は以下の通りとなります:['%Y-%m-%d', # '2006-10-25' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y'] # '10/25/06'加えて、設定内で
USE_L10N=Falseを指定した場合、以下がデフォルトのインプット表示形式に含まれます:['%b %d %Y', # 'Oct 25 2006' '%b %d, %Y', # 'Oct 25, 2006' '%d %b %Y', # '25 Oct 2006' '%d %b, %Y', # '25 Oct, 2006' '%B %d %Y', # 'October 25 2006' '%B %d, %Y', # 'October 25, 2006' '%d %B %Y', # '25 October 2006' '%d %B, %Y'] # '25 October, 2006'表示形式のローカル化 も参照してください。
DateTimeFieldLink to this heading
- class DateTimeField(**kwargs)Link to this definition
デフォルトのウィジェット:
DateTimeInput空の値:
NonePython の
datetime.datetimeオブジェクトに正規化されます。与えられた値が
datetime.datetime、datetime.dateまたは特定の日時の表示形式の文字列のどれかに当てはまるか検証します。エラーメッセージのキー:
required、invalid
1 つの省略可能な引数を取ります:
- input_formatsLink to this definition
有効な
datetime.datetimeオブジェクトに変換する試行に使う表示形式のリストです。
input_formats引数が指定されなかった場合、デフォルトのインプット表示形式は以下の通りとなります:['%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y'] # '10/25/06'表示形式のローカル化 も参照してください。
DecimalFieldLink to this heading
- class DecimalField(**kwargs)Link to this definition
デフォルトのウィジェット:
Field.localizeがFalseのときNumberInput、TrueのときTextInput.空の値:
NonePython の
decimalに正規化されます。Validates that the given value is a decimal. Uses
MaxValueValidatorandMinValueValidatorifmax_valueandmin_valueare provided. Leading and trailing whitespace is ignored.Error message keys:
required,invalid,max_value,min_value,max_digits,max_decimal_places,max_whole_digits
The
max_valueandmin_valueerror messages may contain%(limit_value)s, which will be substituted by the appropriate limit. Similarly, themax_digits,max_decimal_placesandmax_whole_digitserror messages may contain%(max)s.Takes four optional arguments:
- max_valueLink to this definition
- min_valueLink to this definition
These control the range of values permitted in the field, and should be given as
decimal.Decimalvalues.
- max_digitsLink to this definition
The maximum number of digits (those before the decimal point plus those after the decimal point, with leading zeros stripped) permitted in the value.
- decimal_placesLink to this definition
The maximum number of decimal places permitted.
DurationFieldLink to this heading
- class DurationField(**kwargs)Link to this definition
デフォルトのウィジェット:
TextInput空の値:
NonePython の
timedeltaに正規化されます。Validates that the given value is a string which can be converted into a
timedelta. The value must be betweendatetime.timedelta.minanddatetime.timedelta.max.Error message keys:
required,invalid,overflow.
Accepts any format understood by
parse_duration().
EmailFieldLink to this heading
- class EmailField(**kwargs)Link to this definition
デフォルトのウィジェット:
EmailInput空の値:
''(空の文字列)Normalizes to: A string.
Uses
EmailValidatorto validate that the given value is a valid email address, using a moderately complex regular expression.エラーメッセージのキー:
required、invalid
Has two optional arguments for validation,
max_lengthandmin_length. If provided, these arguments ensure that the string is at most or at least the given length.
FileFieldLink to this heading
- class FileField(**kwargs)Link to this definition
デフォルトのウィジェット:
ClearableFileInput空の値:
Noneファイルコンテンツとファイル名を1つのオブジェクトにラッピングした
UploadedFileオブジェクトに正規化されます。Can validate that non-empty file data has been bound to the form.
Error message keys:
required,invalid,missing,empty,max_length
Has two optional arguments for validation,
max_lengthandallow_empty_file. If provided, these ensure that the file name is at most the given length, and that validation will succeed even if the file content is empty.UploadedFileオブジェクトについて詳しく知るには、 ファイルのアップロードのドキュメント を読んでください。フォーム内で
FileFieldを使用する時は、ファイルのデータをフォームにバインディング することも必要です。The
max_lengtherror refers to the length of the filename. In the error message for that key,%(max)dwill be replaced with the maximum filename length and%(length)dwill be replaced with the current filename length.
FilePathFieldLink to this heading
- class FilePathField(**kwargs)Link to this definition
デフォルトのウィジェット:
Select空の値:
''(空の文字列)Normalizes to: A string.
Validates that the selected choice exists in the list of choices.
Error message keys:
required,invalid_choice
The field allows choosing from files inside a certain directory. It takes five extra arguments; only
pathis required:- pathLink to this definition
The absolute path to the directory whose contents you want listed. This directory must exist.
- recursiveLink to this definition
If
False(the default) only the direct contents ofpathwill be offered as choices. IfTrue, the directory will be descended into recursively and all descendants will be listed as choices.
- matchLink to this definition
A regular expression pattern; only files with names matching this expression will be allowed as choices.
- allow_filesLink to this definition
Optional. Either
TrueorFalse. Default isTrue. Specifies whether files in the specified location should be included. Either this orallow_foldersmust beTrue.
- allow_foldersLink to this definition
Optional. Either
TrueorFalse. Default isFalse. Specifies whether folders in the specified location should be included. Either this orallow_filesmust beTrue.
FloatFieldLink to this heading
- class FloatField(**kwargs)Link to this definition
デフォルトのウィジェット:
Field.localizeがFalseのときNumberInput、TrueのときTextInput.空の値:
NonePython の float に正規化されます。
Validates that the given value is a float. Uses
MaxValueValidatorandMinValueValidatorifmax_valueandmin_valueare provided. Leading and trailing whitespace is allowed, as in Python'sfloat()function.Error message keys:
required,invalid,max_value,min_value
Takes two optional arguments for validation,
max_valueandmin_value. These control the range of values permitted in the field.
ImageFieldLink to this heading
- class ImageField(**kwargs)Link to this definition
デフォルトのウィジェット:
ClearableFileInput空の値:
Noneファイルコンテンツとファイル名を1つのオブジェクトにラッピングした
UploadedFileオブジェクトに正規化されます。Validates that file data has been bound to the form. Also uses
FileExtensionValidatorto validate that the file extension is supported by Pillow.Error message keys:
required,invalid,missing,empty,invalid_image
Using an
ImageFieldrequires that Pillow is installed with support for the image formats you use. If you encounter acorrupt imageerror when you upload an image, it usually means that Pillow doesn't understand its format. To fix this, install the appropriate library and reinstall Pillow.When you use an
ImageFieldon a form, you must also remember to bind the file data to the form.After the field has been cleaned and validated, the
UploadedFileobject will have an additionalimageattribute containing the Pillow Image instance used to check if the file was a valid image. Pillow closes the underlying file descriptor after verifying an image, so whilst non-image data attributes, such asformat,height, andwidth, are available, methods that access the underlying image data, such asgetdata()orgetpixel(), cannot be used without reopening the file. For example:>>> from PIL import Image >>> from django import forms >>> from django.core.files.uploadedfile import SimpleUploadedFile >>> class ImageForm(forms.Form): ... img = forms.ImageField() >>> file_data = {'img': SimpleUploadedFile('test.png', <file data>)} >>> form = ImageForm({}, file_data) # Pillow closes the underlying file descriptor. >>> form.is_valid() True >>> image_field = form.cleaned_data['img'] >>> image_field.image <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=191x287 at 0x7F5985045C18> >>> image_field.image.width 191 >>> image_field.image.height 287 >>> image_field.image.format 'PNG' >>> image_field.image.getdata() # Raises AttributeError: 'NoneType' object has no attribute 'seek'. >>> image = Image.open(image_field) >>> image.getdata() <ImagingCore object at 0x7f5984f874b0>Additionally,
UploadedFile.content_typewill be updated with the image's content type if Pillow can determine it, otherwise it will be set toNone.
IntegerFieldLink to this heading
- class IntegerField(**kwargs)Link to this definition
デフォルトのウィジェット:
Field.localizeがFalseのときNumberInput、TrueのときTextInput.空の値:
NoneNormalizes to: A Python integer.
Validates that the given value is an integer. Uses
MaxValueValidatorandMinValueValidatorifmax_valueandmin_valueare provided. Leading and trailing whitespace is allowed, as in Python'sint()function.Error message keys:
required,invalid,max_value,min_value
The
max_valueandmin_valueerror messages may contain%(limit_value)s, which will be substituted by the appropriate limit.Takes two optional arguments for validation:
- max_valueLink to this definition
- min_valueLink to this definition
These control the range of values permitted in the field.
GenericIPAddressFieldLink to this heading
- class GenericIPAddressField(**kwargs)Link to this definition
IPv4 または IPv6 アドレスのいずれかを持つフィールドです。
デフォルトのウィジェット:
TextInput空の値:
''(空の文字列)Normalizes to: A string. IPv6 addresses are normalized as described below.
与えられた値が有効な IP アドレスを表しているか検証します。
エラーメッセージのキー:
required、invalid
IPv6 アドレスは、 RFC 4291 Section 2.2 section 2.2 (同セクションの paragraph 3 で提案された IPv4 のフォーマットの使用を含む) にしたがって、
::ffff:192.0.2.0のように正規化します。たとえば、2001:0::0:01は2001::1と正規化され、::ffff:0a0a:0a0aは::ffff:10.10.10.10と正規化されます。そして、すべての文字は小文字に変換されます。次の2つの省略可能な引数を取ります:
- protocolLink to this definition
有効な入力を指定したプロトコルに限定します。指定できる値は、
both(デフォルト)、IPv4またはIPv6です。大文字・小文字は無視されます。
- unpack_ipv4Link to this definition
IPv4 にマッピングされた
::ffff:192.0.2.1のようなアドレスをアンパックします。このオプションを有効にすると、このアドレスは192.0.2.1とアンパックされます。デフォルトは無効です。protocolが'both'に設定されている場合にだけ使用できます。
MultipleChoiceFieldLink to this heading
- class MultipleChoiceField(**kwargs)Link to this definition
デフォルトのウィジェット:
SelectMultiple空の値:
[](空のリスト)Normalizes to: A list of strings.
Validates that every value in the given list of values exists in the list of choices.
Error message keys:
required,invalid_choice,invalid_list
The
invalid_choiceerror message may contain%(value)s, which will be replaced with the selected choice.Takes one extra required argument,
choices, as forChoiceField.
TypedMultipleChoiceFieldLink to this heading
- class TypedMultipleChoiceField(**kwargs)Link to this definition
Just like a
MultipleChoiceField, exceptTypedMultipleChoiceFieldtakes two extra arguments,coerceandempty_value.デフォルトのウィジェット:
SelectMultiple空の値:
empty_valueとして渡したものNormalizes to: A list of values of the type provided by the
coerceargument.Validates that the given values exists in the list of choices and can be coerced.
Error message keys:
required,invalid_choice
The
invalid_choiceerror message may contain%(value)s, which will be replaced with the selected choice.Takes two extra arguments,
coerceandempty_value, as forTypedChoiceField.
NullBooleanFieldLink to this heading
- class NullBooleanField(**kwargs)Link to this definition
デフォルトのウィジェット:
NullBooleanSelect空の値:
NoneNormalizes to: A Python
True,FalseorNonevalue.Validates nothing (i.e., it never raises a
ValidationError).
RegexFieldLink to this heading
- class RegexField(**kwargs)Link to this definition
デフォルトのウィジェット:
TextInput空の値:
''(空の文字列)Normalizes to: A string.
Uses
RegexValidatorto validate that the given value matches a certain regular expression.エラーメッセージのキー:
required、invalid
Takes one required argument:
- regexLink to this definition
A regular expression specified either as a string or a compiled regular expression object.
Also takes
max_length,min_length, andstrip, which work just as they do forCharField.- stripLink to this definition
Defaults to
False. If enabled, stripping will be applied before the regex validation.
SlugFieldLink to this heading
- class SlugField(**kwargs)Link to this definition
デフォルトのウィジェット:
TextInput空の値:
''(空の文字列)Normalizes to: A string.
Uses
validate_slugorvalidate_unicode_slugto validate that the given value contains only letters, numbers, underscores, and hyphens.Error messages:
required,invalid
This field is intended for use in representing a model
SlugFieldin forms.Takes an optional parameter:
- allow_unicodeLink to this definition
A boolean instructing the field to accept Unicode letters in addition to ASCII letters. Defaults to
False.
TimeFieldLink to this heading
- class TimeField(**kwargs)Link to this definition
Default widget:
TimeInput空の値:
NonePython の
datetime.timeオブジェクトに正規化されます。Validates that the given value is either a
datetime.timeor string formatted in a particular time format.エラーメッセージのキー:
required、invalid
1 つの省略可能な引数を取ります:
- input_formatsLink to this definition
A list of formats used to attempt to convert a string to a valid
datetime.timeobject.
input_formats引数が指定されなかった場合、デフォルトのインプット表示形式は以下の通りとなります:'%H:%M:%S', # '14:30:59' '%H:%M', # '14:30'
URLFieldLink to this heading
- class URLField(**kwargs)Link to this definition
デフォルトのウィジェット:
URLInput空の値:
''(空の文字列)Normalizes to: A string.
Uses
URLValidatorto validate that the given value is a valid URL.エラーメッセージのキー:
required、invalid
以下の省略可能な引数を取ります。
- max_lengthLink to this definition
- min_lengthLink to this definition
These are the same as
CharField.max_lengthandCharField.min_length.
UUIDFieldLink to this heading
- class UUIDField(**kwargs)Link to this definition
-
This field will accept any string format accepted as the
hexargument to theUUIDconstructor.
Slightly complex built-in Field classesLink to this heading
ComboFieldLink to this heading
- class ComboField(**kwargs)Link to this definition
デフォルトのウィジェット:
TextInput空の値:
''(空の文字列)Normalizes to: A string.
Validates the given value against each of the fields specified as an argument to the
ComboField.エラーメッセージのキー:
required、invalid
Takes one extra required argument:
- fieldsLink to this definition
The list of fields that should be used to validate the field's value (in the order in which they are provided).
>>> from django.forms import ComboField >>> f = ComboField(fields=[CharField(max_length=20), EmailField()]) >>> f.clean('test@example.com') 'test@example.com' >>> f.clean('longemailaddress@example.com') Traceback (most recent call last): ... ValidationError: ['Ensure this value has at most 20 characters (it has 28).']
MultiValueFieldLink to this heading
- class MultiValueField(fields=(), **kwargs)Link to this definition
デフォルトのウィジェット:
TextInput空の値:
''(空の文字列)Normalizes to: the type returned by the
compressmethod of the subclass.Validates the given value against each of the fields specified as an argument to the
MultiValueField.Error message keys:
required,invalid,incomplete
Aggregates the logic of multiple fields that together produce a single value.
This field is abstract and must be subclassed. In contrast with the single-value fields, subclasses of
MultiValueFieldmust not implementclean()but instead - implementcompress().Takes one extra required argument:
- fieldsLink to this definition
A tuple of fields whose values are cleaned and subsequently combined into a single value. Each value of the field is cleaned by the corresponding field in
fields-- the first value is cleaned by the first field, the second value is cleaned by the second field, etc. Once all fields are cleaned, the list of clean values is combined into a single value bycompress().
Also takes some optional arguments:
- require_all_fieldsLink to this definition
Defaults to
True, in which case arequiredvalidation error will be raised if no value is supplied for any field.When set to
False, theField.requiredattribute can be set toFalsefor individual fields to make them optional. If no value is supplied for a required field, anincompletevalidation error will be raised.A default
incompleteerror message can be defined on theMultiValueFieldsubclass, or different messages can be defined on each individual field. For example:from django.core.validators import RegexValidator class PhoneField(MultiValueField): def __init__(self, **kwargs): # Define one message for all fields. error_messages = { 'incomplete': 'Enter a country calling code and a phone number.', } # Or define a different message for each field. fields = ( CharField( error_messages={'incomplete': 'Enter a country calling code.'}, validators=[ RegexValidator(r'^[0-9]+$', 'Enter a valid country calling code.'), ], ), CharField( error_messages={'incomplete': 'Enter a phone number.'}, validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid phone number.')], ), CharField( validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid extension.')], required=False, ), ) super().__init__( error_messages=error_messages, fields=fields, require_all_fields=False, **kwargs )
- widgetLink to this definition
Must be a subclass of
django.forms.MultiWidget. Default value isTextInput, which probably is not very useful in this case.
- compress(data_list)Link to this definition
Takes a list of valid values and returns a "compressed" version of those values -- in a single value. For example,
SplitDateTimeFieldis a subclass which combines a time field and a date field into adatetimeobject.This method must be implemented in the subclasses.
SplitDateTimeFieldLink to this heading
- class SplitDateTimeField(**kwargs)Link to this definition
デフォルトのウィジェット:
SplitDateTimeWidget空の値:
NonePython の
datetime.datetimeオブジェクトに正規化されます。Validates that the given value is a
datetime.datetimeor string formatted in a particular datetime format.Error message keys:
required,invalid,invalid_date,invalid_time
次の2つの省略可能な引数を取ります:
- input_date_formatsLink to this definition
文字列を有効な
datetime.dateオブジェクトに変換する試行に使う表示形式のリストです。
If no
input_date_formatsargument is provided, the default input formats forDateFieldare used.- input_time_formatsLink to this definition
A list of formats used to attempt to convert a string to a valid
datetime.timeobject.
If no
input_time_formatsargument is provided, the default input formats forTimeFieldare used.
Fields which handle relationshipsLink to this heading
Two fields are available for representing relationships between
models: ModelChoiceField and
ModelMultipleChoiceField. Both of these fields require a
single queryset parameter that is used to create the choices for
the field. Upon form validation, these fields will place either one
model object (in the case of ModelChoiceField) or multiple model
objects (in the case of ModelMultipleChoiceField) into the
cleaned_data dictionary of the form.
For more complex uses, you can specify queryset=None when declaring the
form field and then populate the queryset in the form's __init__()
method:
class FooMultipleChoiceForm(forms.Form):
foo_select = forms.ModelMultipleChoiceField(queryset=None)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['foo_select'].queryset = ...
ModelChoiceFieldLink to this heading
- class ModelChoiceField(**kwargs)Link to this definition
デフォルトのウィジェット:
Select空の値:
Nonemodel インスタンスに正規化されます。
Validates that the given id exists in the queryset.
Error message keys:
required,invalid_choice
Allows the selection of a single model object, suitable for representing a foreign key. Note that the default widget for
ModelChoiceFieldbecomes impractical when the number of entries increases. You should avoid using it for more than 100 items.A single argument is required:
- querysetLink to this definition
A
QuerySetof model objects from which the choices for the field are derived and which is used to validate the user's selection. It's evaluated when the form is rendered.
ModelChoiceFieldalso takes two optional arguments:- empty_labelLink to this definition
By default the
<select>widget used byModelChoiceFieldwill have an empty choice at the top of the list. You can change the text of this label (which is"---------"by default) with theempty_labelattribute, or you can disable the empty label entirely by settingempty_labeltoNone:# A custom empty label field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)") # No empty label field2 = forms.ModelChoiceField(queryset=..., empty_label=None)Note that if a
ModelChoiceFieldis required and has a default initial value, no empty choice is created (regardless of the value ofempty_label).
- to_field_nameLink to this definition
This optional argument is used to specify the field to use as the value of the choices in the field's widget. Be sure it's a unique field for the model, otherwise the selected value could match more than one object. By default it is set to
None, in which case the primary key of each object will be used. For example:# No custom to_field_name field1 = forms.ModelChoiceField(queryset=...)would yield:
<select id="id_field1" name="field1"> <option value="obj1.pk">Object1</option> <option value="obj2.pk">Object2</option> ... </select>and:
# to_field_name provided field2 = forms.ModelChoiceField(queryset=..., to_field_name="name")would yield:
<select id="id_field2" name="field2"> <option value="obj1.name">Object1</option> <option value="obj2.name">Object2</option> ... </select>
The
__str__()method of the model will be called to generate string representations of the objects for use in the field's choices. To provide customized representations, subclassModelChoiceFieldand overridelabel_from_instance. This method will receive a model object and should return a string suitable for representing it. For example:from django.forms import ModelChoiceField class MyModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return "My Object #%i" % obj.id
ModelMultipleChoiceFieldLink to this heading
- class ModelMultipleChoiceField(**kwargs)Link to this definition
デフォルトのウィジェット:
SelectMultiple空の値: 空の
QuerySet(self.queryset.none())Normalizes to: A
QuerySetof model instances.Validates that every id in the given list of values exists in the queryset.
Error message keys:
required,list,invalid_choice,invalid_pk_value
The
invalid_choicemessage may contain%(value)sand theinvalid_pk_valuemessage may contain%(pk)s, which will be substituted by the appropriate values.Allows the selection of one or more model objects, suitable for representing a many-to-many relation. As with
ModelChoiceField, you can uselabel_from_instanceto customize the object representations.A single argument is required:
- querysetLink to this definition
Same as
ModelChoiceField.queryset.
1 つの省略可能な引数を取ります:
- to_field_nameLink to this definition
Same as
ModelChoiceField.to_field_name.
Creating custom fieldsLink to this heading
If the built-in Field classes don't meet your needs, you can easily create
custom Field classes. To do this, just create a subclass of
django.forms.Field. Its only requirements are that it implement a
clean() method and that its __init__() method accept the core arguments
mentioned above (required, label, initial, widget,
help_text).
You can also customize how a field will be accessed by overriding
get_bound_field().