表单字段¶
当您创建 Form
类时,最重要的部分是定义窗体的字段。每个字段都有自定义验证逻辑,以及一些其他钩子。
尽管您将使用 Field
类的主要方法是在 Form
类中,您还可以实例化它们,并直接使用它们来更好地了解它们如何工作。每个 Field
实例都有一个 clean()
方法,它接受一个参数,并引发一个 django.forms.ValidationError
异常或返回clean值:
>>> 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
类构造函数至少采用这些参数。一些 Field
类需要额外的,特定于字段的参数,但以下应该接受 always:
required
¶
-
Field.
required
¶
默认情况下,每个 Field
类假定该值是必需的,因此如果您传递一个空值 - None
或空字符串(""
),则 clean()
将引发 ValidationError
异常:
>>> 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'
要指定字段是 not 所需的,请将 required=False
传递给 Field
构造函数:
>>> 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'
如果 Field
有 required=False
,并且您通过 clean()
一个空值,则 clean()
将返回一个 normalized 空值,而不是提高 ValidationError
。对于 CharField
,这将是一个Unicode空字符串。对于其他 Field
类,它可能是 None
。 (不同的字段不同)。
label
¶
-
Field.
label
¶
label
参数允许您为此字段指定“人性化”标签。这在 Field
显示在 Form
中时使用。
如上面的“以HTML格式输出表单”中所述,Field
的默认标签是通过将所有下划线转换为空格而将上下文转换为第一个字母从字段名称生成的。如果缺省行为不能产生足够的标签,请指定 label
。
这里有一个完整的示例 Form
实现其两个字段的 label
。我们已经指定了 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" required /></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" required /></td></tr>
label_suffix
¶
-
Field.
label_suffix
¶
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>
initial
¶
-
Field.
initial
¶
initial
参数允许您指定在未绑定 Form
中呈现此 Field
时要使用的初始值。
要指定动态初始数据,请参阅 Form.initial
参数。
这种情况下的用例是当你想显示一个“空”形式,其中一个字段被初始化为一个特定的值。例如:
>>> 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>
你可能在想,为什么不只是传递一个初始值的字典作为数据显示窗体时?好吧,如果你这样做,你将触发验证,HTML输出将包括任何验证错误:
>>> 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>
这就是为什么 initial
值只显示未绑定的窗体。对于绑定的表单,HTML输出将使用绑定的数据。
还要注意,如果未给出特定字段的值,则 initial
值将在验证中 not 用作“后备”数据。 initial
值是用于初始形式显示的 only:
>>> 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.']}
而不是一个常量,你也可以传递任何可调用:
>>> 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>
只有在显示未绑定的窗体时才会评估可调用项,而不是在定义它时。
help_text
¶
-
Field.
help_text
¶
help_text
参数允许您为此 Field
指定描述性文本。如果您提供 help_text
,则当通过方便 Form
方法(例如,as_ul()
)之一呈现 Field
时,将显示在 Field
旁边。
与模型字段的 help_text
一样,此值不会在自动生成的表单中进行HTML转义。
这里有一个完整的示例 Form
实现其两个字段的 help_text
。我们已经指定了 auto_id=False
来简化输出:
>>> 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_messages
¶
-
Field.
error_messages
¶
error_messages
参数允许您覆盖字段将引发的默认消息。传入具有与要覆盖的错误消息匹配的键的字典。例如,这里是默认的错误消息:
>>> from django import forms
>>> generic = forms.CharField()
>>> generic.clean('')
Traceback (most recent call last):
...
ValidationError: ['This field is required.']
这里是一个自定义的错误信息:
>>> name = forms.CharField(error_messages={'required': 'Please enter your name'})
>>> name.clean('')
Traceback (most recent call last):
...
ValidationError: ['Please enter your name']
在下面的 built-in Field classes 部分中,每个 Field
定义它使用的错误消息键。
检查字段数据是否已更改¶
内置 Field
类¶
当然,forms
库提供了一组代表常见验证需求的 Field
类。本节记录每个内置字段。
对于每个字段,我们描述如果您不指定 widget
时使用的默认小部件。我们还指定了当您提供空值时返回的值(请参阅上面的 required
部分以了解这意味着什么)。
BooleanField
¶
-
class
BooleanField
(**kwargs)[源代码]¶ 默认小部件:
CheckboxInput
空值:
False
规范化为:Python
True
或False
值。如果字段具有
required=True
,则验证值为True
(例如,选中复选框)。错误消息键:
required
注解
由于所有
Field
子类都默认具有required=True
,因此此处的验证条件很重要。如果您要在表单中包含布林值(可以是True
或False
)(例如已选中或未选中的复选框),则必须记住在创建BooleanField
时传入required=False
。
CharField
¶
ChoiceField
¶
-
class
ChoiceField
(**kwargs)[源代码]¶ 默认小部件:
Select
空值:
''
(空字符串)规范化为:Unicode对象。
验证给定值存在于选择列表中。
错误消息键:
required
,invalid_choice
invalid_choice
错误消息可能包含%(value)s
,将用选定的选项替换。需要一个额外的必需参数:
-
choices
¶ 要用作此字段的选择的2元组的可迭代(例如,列表或元组),或返回此类可迭代的可调用。此参数接受与模型字段的
choices
参数相同的格式。有关详细信息,请参阅 关于选择的模型字段参考文档。如果参数是可调用的,则在每次初始化字段的形式时对其进行求值。
TypedChoiceField
¶
-
class
TypedChoiceField
(**kwargs)[源代码]¶ 就像
ChoiceField
,除了TypedChoiceField
需要两个额外的参数,coerce
和empty_value
。默认小部件:
Select
空值:您作为
empty_value
提供的任何内容。规范化为:由
coerce
参数提供的类型的值。验证给定值存在于选项列表中,并且可以强制。
错误消息键:
required
,invalid_choice
需要额外的参数:
-
coerce
¶ 一个函数,它接受一个参数并返回强制值。例子包括内置的
int
,float
,bool
和其他类型。默认为标识函数。注意,强制在输入验证之后发生,因此可以强制为choices
中不存在的值。
-
empty_value
¶ 用于表示“空”的值。默认为空字符串;
None
是另一个常见的选择。请注意,此值不会由coerce
参数中给出的函数强制,因此请相应选择它。
DateField
¶
-
class
DateField
(**kwargs)[源代码]¶ 默认小部件:
DateInput
空值:
None
规范化为:Python
datetime.date
对象。验证给定值是
datetime.date
,datetime.datetime
或以特定日期格式格式化的字符串。错误消息键:
required
,invalid
采用一个可选参数:
-
input_formats
¶ 用于尝试将字符串转换为有效
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'
参见 格式定位。
DateTimeField
¶
-
class
DateTimeField
(**kwargs)[源代码]¶ 默认小部件:
DateTimeInput
空值:
None
规范化为:Python
datetime.datetime
对象。验证给定值是
datetime.datetime
,datetime.date
或以特定日期时间格式格式化的字符串。错误消息键:
required
,invalid
采用一个可选参数:
-
input_formats
¶ 用于尝试将字符串转换为有效
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'
参见 格式定位。
DecimalField
¶
-
class
DecimalField
(**kwargs)[源代码]¶ 默认小部件:
NumberInput
,当Field.localize
是False
,否则TextInput
。空值:
None
规范化为:Python
decimal
。验证给定值是十进制。前导和尾随空格被忽略。
错误消息键:
required
,invalid
,max_value
,min_value
,max_digits
,max_decimal_places
,max_whole_digits
max_value
和min_value
错误消息可能包含%(limit_value)s
,将由适当的限制替换。类似地,max_digits
,max_decimal_places
和max_whole_digits
错误消息可以包含%(max)s
。有四个可选参数:
-
max_value
¶
-
min_value
¶ 它们控制字段中允许的值的范围,并且应该作为
decimal.Decimal
值给出。
-
max_digits
¶ 在值中允许的最大位数(小数点前的数字加上小数点后的数字,带有前导零)。
-
decimal_places
¶ 允许的最大小数位数。
DurationField
¶
-
class
DurationField
(**kwargs)[源代码]¶ -
接受
parse_duration()
理解的任何格式。
EmailField
¶
-
class
EmailField
(**kwargs)[源代码]¶ 默认小部件:
EmailInput
空值:
''
(空字符串)规范化为:Unicode对象。
使用中度复杂的正则表达式验证给定值是有效的电子邮件地址。
错误消息键:
required
,invalid
有两个可选的验证参数,
max_length
和min_length
。如果提供,这些参数确保字符串至多或至少为给定长度。
FileField
¶
-
class
FileField
(**kwargs)[源代码]¶ 默认小部件:
ClearableFileInput
空值:
None
规范化为:将文件内容和文件名包装到单个对象中的
UploadedFile
对象。可以验证非空文件数据已绑定到表单。
错误消息键:
required
,invalid
,missing
,empty
,max_length
有两个可选的验证参数,
max_length
和allow_empty_file
。如果提供,这些确保文件名称最多为给定长度,并且即使文件内容为空,验证也将成功。要了解有关
UploadedFile
对象的更多信息,请参阅 文件上传文档。当您在表单中使用
FileField
时,您还必须记住 将文件数据绑定到表单。max_length
错误指的是文件名的长度。在该键的错误消息中,%(max)d
将替换为最大文件名长度,%(length)d
将替换为当前文件名长度。
FilePathField
¶
-
class
FilePathField
(**kwargs)[源代码]¶ 默认小部件:
Select
空值:
None
规范化为:unicode对象
验证所选选项是否存在于选项列表中。
错误消息键:
required
,invalid_choice
该字段允许从某个目录中的文件进行选择。它需要五个额外的参数;只需要
path
:-
path
¶ 要列出其内容的目录的绝对路径。此目录必须存在。
-
recursive
¶ 如果
False
(默认)只有path
的直接内容将作为选择提供。如果True
,目录将递归递归,所有后代将被列为选择。
-
match
¶ 正则表达式模式;仅允许具有与此表达式匹配的名称的文件作为选择。
-
allow_files
¶ 可选的。
True
或False
。默认为True
。指定是否应包括指定位置中的文件。这个或allow_folders
必须是True
。
-
allow_folders
¶ 可选的。
True
或False
。默认为False
。指定是否应包括指定位置中的文件夹。这个或allow_files
必须是True
。
FloatField
¶
-
class
FloatField
(**kwargs)[源代码]¶ 默认小部件:
NumberInput
,当Field.localize
是False
,否则TextInput
。空值:
None
规范化为:Python浮动。
验证给定值是一个浮点数。允许前导和尾随空格,如在Python的
float()
函数中。错误消息键:
required
,invalid
,max_value
,min_value
采用两个可选参数进行验证,
max_value
和min_value
。它们控制字段中允许的值的范围。
ImageField
¶
-
class
ImageField
(**kwargs)[源代码]¶ 默认小部件:
ClearableFileInput
空值:
None
规范化为:将文件内容和文件名包装到单个对象中的
UploadedFile
对象。验证文件数据已绑定到表单,并且该文件具有Pillow理解的图像格式。
错误消息键:
required
,invalid
,missing
,empty
,invalid_image
使用
ImageField
需要安装 Pillow 以支持您使用的图像格式。如果在上传图像时遇到corrupt image
错误,通常意味着Pillow不能理解其格式。要解决这个问题,请安装相应的库并重新安装Pillow。当您在表单上使用
ImageField
时,您还必须记住 将文件数据绑定到表单。在该字段被清理和验证之后,
UploadedFile
对象将具有包含用于检查文件是否是有效图像的Pillow Image 实例的附加image
属性。此外,UploadedFile.content_type
将更新与图像的内容类型,如果Pillow可以确定它,否则它将被设置为None
。
IntegerField
¶
-
class
IntegerField
(**kwargs)[源代码]¶ 默认小部件:
NumberInput
,当Field.localize
是False
,否则TextInput
。空值:
None
规范化为:Python整数或长整数。
验证给定值是一个整数。允许前导和尾随空格,如在Python的
int()
函数中。错误消息键:
required
,invalid
,max_value
,min_value
max_value
和min_value
错误消息可能包含%(limit_value)s
,将由适当的限制替换。采用两个可选参数进行验证:
-
max_value
¶
-
min_value
¶
它们控制字段中允许的值的范围。
GenericIPAddressField
¶
-
class
GenericIPAddressField
(**kwargs)[源代码]¶ 包含IPv4或IPv6地址的字段。
默认小部件:
TextInput
空值:
''
(空字符串)规范化为:Unicode对象。 IPv6地址如下所述进行归一化。
验证给定值是有效的IP地址。
错误消息键:
required
,invalid
IPv6地址规范化遵循 RFC 4291#section-2.2 第2.2节,包括使用该节第3段中建议的IPv4格式,如
::ffff:192.0.2.0
。例如,2001:0::0:01
将归一化为2001::1
,而::ffff:0a0a:0a0a
归一化为::ffff:10.10.10.10
。所有字符都转换为小写。有两个可选参数:
-
protocol
¶ 限制指定协议的有效输入。接受的值为
both
(默认),IPv4
或IPv6
。匹配不区分大小写。
-
unpack_ipv4
¶ 解开IPv4映射地址(如
::ffff:192.0.2.1
)。如果启用此选项,则该地址将解包到192.0.2.1
。默认为禁用。只能在protocol
设置为'both'
时使用。
MultipleChoiceField
¶
-
class
MultipleChoiceField
(**kwargs)[源代码]¶ 默认小部件:
SelectMultiple
空值:
[]
(空列表)规范化为:Unicode对象的列表。
验证给定值列表中的每个值都存在于选择列表中。
错误消息键:
required
,invalid_choice
,invalid_list
invalid_choice
错误消息可能包含%(value)s
,将用选定的选项替换。需要一个额外的必要参数,
choices
,如ChoiceField
。
TypedMultipleChoiceField
¶
-
class
TypedMultipleChoiceField
(**kwargs)[源代码]¶ 就像
MultipleChoiceField
,除了TypedMultipleChoiceField
需要两个额外的参数,coerce
和empty_value
。默认小部件:
SelectMultiple
空值:您作为
empty_value
提供的任何内容规范化为:由
coerce
参数提供的类型的值的列表。验证给定值存在于选择列表中并且可以强制。
错误消息键:
required
,invalid_choice
invalid_choice
错误消息可能包含%(value)s
,将用选定的选项替换。需要两个额外的参数,
coerce
和empty_value
,如TypedChoiceField
。
NullBooleanField
¶
-
class
NullBooleanField
(**kwargs)[源代码]¶ 默认小部件:
NullBooleanSelect
空值:
None
规范化为:Python
True
,False
或None
值。什么都不验证(即,它从来没有提出
ValidationError
)。
RegexField
¶
SlugField
¶
TimeField
¶
URLField
¶
稍微复杂的内置 Field
类¶
ComboField
¶
-
class
ComboField
(**kwargs)[源代码]¶ 默认小部件:
TextInput
空值:
''
(空字符串)规范化为:Unicode对象。
根据指定为
ComboField
参数的每个字段验证给定值。错误消息键:
required
,invalid
需要一个额外的必需参数:
-
fields
¶ 应用于验证字段值的字段列表(按提供它们的顺序)。
>>> 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).']
MultiValueField
¶
-
class
MultiValueField
(fields=(), **kwargs)[源代码]¶ 默认小部件:
TextInput
空值:
''
(空字符串)规范化为:子类的
compress
方法返回的类型。根据指定为
MultiValueField
参数的每个字段验证给定值。错误消息键:
required
,invalid
,incomplete
聚合一起产生单个值的多个字段的逻辑。
此字段是抽象的,必须是子类。与单值字段相反,
MultiValueField
的子类不能实现clean()
,而是实现compress()
。需要一个额外的必需参数:
-
fields
¶ 字段的元组,其值被清除并随后组合成单个值。字段的每个值由
fields
中的相应字段清除 - 第一个值由第一个字段清除,第二个值由第二个字段清除等。一旦清除所有字段,清除值的列表将合并通过compress()
转换为单个值。
还需要一个额外的可选参数:
-
require_all_fields
¶ 默认为
True
,在这种情况下,如果没有为任何字段提供值,将会引发required
验证错误。当设置为
False
时,Field.required
属性可以设置为False
用于单个字段,使它们可选。如果没有为必填字段提供值,则会引发incomplete
验证错误。可以在
MultiValueField
子类上定义默认incomplete
错误消息,或者可以在每个单独字段上定义不同的消息。例如:from django.core.validators import RegexValidator class PhoneField(MultiValueField): def __init__(self, *args, **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(PhoneField, self).__init__( error_messages=error_messages, fields=fields, require_all_fields=False, *args, **kwargs )
-
widget
¶ 必须是
django.forms.MultiWidget
的子类。默认值是TextInput
,这在这种情况下可能不是非常有用。
-
compress
(data_list)[源代码]¶ 获取有效值的列表,并在单个值中返回这些值的“压缩”版本。例如,
SplitDateTimeField
是将时间字段和日期字段组合成datetime
对象的子类。此方法必须在子类中实现。
SplitDateTimeField
¶
-
class
SplitDateTimeField
(**kwargs)[源代码]¶ 默认小部件:
SplitDateTimeWidget
空值:
None
规范化为:Python
datetime.datetime
对象。验证给定值是以特定日期时间格式格式化的
datetime.datetime
或字符串。错误消息键:
required
,invalid
,invalid_date
,invalid_time
有两个可选参数:
-
input_date_formats
¶ 用于尝试将字符串转换为有效
datetime.date
对象的格式列表。
如果没有提供
input_date_formats
参数,则使用DateField
的默认输入格式。-
input_time_formats
¶ 用于尝试将字符串转换为有效
datetime.time
对象的格式列表。
如果没有提供
input_time_formats
参数,则使用TimeField
的默认输入格式。
处理关系的字段¶
两个字段可用于表示模型之间的关系:ModelChoiceField
和 ModelMultipleChoiceField
。这两个字段都需要一个 queryset
参数,用于创建字段的选择。在表单验证时,这些字段将将一个模型对象(在 ModelChoiceField
的情况下)或多个模型对象(在 ModelMultipleChoiceField
的情况下)放置到表单的 cleaned_data
字典中。
对于更复杂的用法,您可以在声明表单字段时指定 queryset=None
,然后在表单的 __init__()
方法中填充 queryset
:
class FooMultipleChoiceForm(forms.Form):
foo_select = forms.ModelMultipleChoiceField(queryset=None)
def __init__(self, *args, **kwargs):
super(FooMultipleChoiceForm, self).__init__(*args, **kwargs)
self.fields['foo_select'].queryset = ...
ModelChoiceField
¶
-
class
ModelChoiceField
(**kwargs)[源代码]¶ 默认小部件:
Select
空值:
None
规范化为:模型实例。
验证给定的id存在于查询集中。
错误消息键:
required
,invalid_choice
允许选择适合表示外键的单个模型对象。请注意,当条目数增加时,
ModelChoiceField
的默认窗口小部件变得不切实际。你应该避免使用它超过100项。需要单个参数:
-
queryset
¶ 将从中导出字段的选择的模型对象的
QuerySet
,并且将用于验证用户的选择。
ModelChoiceField
还接受两个可选参数:-
empty_label
¶ 默认情况下,
ModelChoiceField
使用的<select>
小部件在列表顶部将有一个空选项。您可以使用empty_label
属性更改此标签(默认为"---------"
)的文本,也可以通过将empty_label
设置为None
来完全禁用空标签:# A custom empty label field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)") # No empty label field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
注意,如果需要
ModelChoiceField
并且具有默认初始值,则不创建空选项(不管empty_label
的值如何)。
-
to_field_name
¶ 此可选参数用于指定要用作字段窗口小部件中选项的值的字段。确保它是模型的唯一字段,否则选定的值可以匹配多个对象。默认情况下,它设置为
None
,在这种情况下,将使用每个对象的主键。例如:# No custom to_field_name field1 = forms.ModelChoiceField(queryset=...)
将产生:
<select id="id_field1" name="field1"> <option value="obj1.pk">Object1</option> <option value="obj2.pk">Object2</option> ... </select>
和:
# to_field_name provided field2 = forms.ModelChoiceField(queryset=..., to_field_name="name")
将产生:
<select id="id_field2" name="field2"> <option value="obj1.name">Object1</option> <option value="obj2.name">Object2</option> ... </select>
将调用模型的
__str__
(__unicode__
on Python 2)方法来生成对象的字符串表示,以在字段的选择中使用;提供自定义表示,子类ModelChoiceField
和覆盖label_from_instance
。此方法将接收一个模型对象,并应返回一个适合表示它的字符串。例如:from django.forms import ModelChoiceField class MyModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return "My Object #%i" % obj.id
ModelMultipleChoiceField
¶
-
class
ModelMultipleChoiceField
(**kwargs)[源代码]¶ 默认小部件:
SelectMultiple
空值:空的
QuerySet
(self.queryset.none())规范化为:模型实例的
QuerySet
。验证在给定的值列表中的每个id存在于查询集中。
错误消息键:
required
,list
,invalid_choice
,invalid_pk_value
invalid_choice
消息可以包含%(value)s
,并且invalid_pk_value
消息可以包含%(pk)s
,其将被适当的值代替。允许选择适合于表示多对多关系的一个或多个模型对象。与
ModelChoiceField
一样,您可以使用label_from_instance
来自定义对象表示。需要单个参数:
-
queryset
¶
采用一个可选参数:
-
to_field_name
¶
创建自定义字段¶
如果内置的 Field
类不能满足您的需要,您可以轻松创建自定义 Field
类。为此,只需创建一个 django.forms.Field
的子类。其唯一的要求是它实现 clean()
方法,并且其 __init__()
方法接受上述核心参数(required
,label
,initial
,widget
,help_text
)。
您还可以通过覆盖 get_bound_field()
来自定义字段的访问方式。