创建一个Form
类时,最重要的部分是定义表单的字段。 每个字段都可以有自定义的验证逻辑,以及一些其它的钩子。
虽然Field
类主要使用在Form
类中,但你也可以直接实例化它们来使用,以便更好地了解它们是如何工作的。 每个django.forms.ValidationError
实例都有一个clean()
方法, 它接受一个参数,然后返回“清洁的”数据或者抛出一个Field
异常:
>>> from django import forms
>>> f = forms.EmailField()
>>> f.clean('[email protected]')
'[email protected]'
>>> f.clean('invalid email address')
Traceback (most recent call last):
...
ValidationError: ['Enter a valid email address.']
每个Field
类的构造函数至少接受这些参数。 有些Field
类接受额外的、字段特有的参数,但以下参数应该总是能接受:
required
¶Field.
required
¶默认情况下,每个""
类都假设必需有值,所以如果你传递一个空的值 —— 不管是None
还是空字符串(Field
) —— 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'
若要表示一个字段不是必需的,请传递Field
给required=False
的构造函数:
>>> 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'
如果ValidationError
具有clean()
,而你传递给required=False
一个空值,Field
将返回一个转换后的空值而不是引发clean()
。 例如CharField
,它将是一个空的Unicode 字符串。
对于其它Field
类,它可能是None
。 (每个字段各不相同)。
所需表单字段的小部件具有required
HTML属性。 将Form.use_required_attribute
属性设置为False
以禁用它。 窗体中不包含required
属性,因为在添加和删除窗体时浏览器验证可能不正确。
添加了required
HTML属性的支持。
label
¶Field.
label
¶label
参数让你指定字段“对人类友好”的label。 当Field
在Form
中显示时将用到它。
正如在前面“输出表单为HTML”中解释的,Field
默认label 是通过将字段名中所有的下划线转换成空格并大写第一个字母生成的。 如果默认的标签不合适,可以指定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" /></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
¶Form
参数让你指定渲染未绑定的Field
中的initial
时使用的初始值。
若要指定动态的初始数据,参见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
值不会作为“后备”的数据。 initial
值只用于原始表单的显示:
>>> 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
的描述文本。 如果提供Field
,在通过Field
的便捷方法(例如,help_text
)渲染Form
时,它将紧接着as_ul()
显示。
像模型字段的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']
在下面的内建的字段一节中,每个Field
都定义了它自己的错误信息。
Field
类¶自然,forms
的库会带有一系列表示常见需求的Field
。 这一节记录每个内建字段。
对于每个字段,我们描述默认的widget
。 我们还会指出提供空值时的返回值(参见上文的required
以理解它的含义)。
BooleanField
¶BooleanField
(**kwargs)[source]¶CheckboxInput
False
True
或 False
。True
,验证值是否为required=True
(例如复选框被勾上)。required
注
因为所有的Field
子类都默认带有required=True
,这里的验证条件很重要。 如果你希望表单中包含一个既可以为True
也可以为False
的布尔值(例如,复选框可以勾上也可以不勾上),你必须要记住在创建BooleanField
时传递required=False
。
CharField
¶CharField
(**kwargs)[source]¶TextInput
empty_value
给出的任何值。max_length
或min_length
。
否则,所有的输入都是合法的。min_length
, max_length
, required
有三个可选参数进行验证:
max_length
¶min_length
¶如果提供,这两个参数将确保字符串的最大和最小长度。
strip
¶如果True
(默认),该值将被剥离前导和尾随空格。
empty_value
¶用来表示“空”的值。 默认为空字符串。
ChoiceField
¶ChoiceField
(**kwargs)[source]¶Select
''
(一个空字符串)required
, invalid_choice
invalid_choice
错误消息可能包含%(value)s
,它将被选择的选项替换掉。
还有一个参数:
choices
¶用来作为该字段选项的一个二元组组成的可迭代对象(例如,列表或元组)或者一个可调用对象。
参数的格式与模型字段的choices
参数相同。 更多细节参见model field reference documentation on
choices。 如果参数是可调用的,它在字段的表单初始化时求值。
默认为空列表。
TypedChoiceField
¶TypedChoiceField
(**kwargs)[source]¶就像ChoiceField
一样,除了TypedChoiceField
还有两个额外的参数:coerce
和empty_value
。
Select
empty_value
给出的任何值。coerce
参数类型的值。required
, invalid_choice
接收的额外参数:
coerce
¶接收一个参数并返回强制转换后的值的一个函数。 例如内建的bool
、float
、int
和其它类型。 默认为id 函数。 注意强制转换在输入验证结束后发生,所以它可能强制转换不在 choices
中的值。
empty_value
¶用于表示“空”的值。默认为空字符串; None
是这里的另一个常见选择。 注意这个值不会被coerce
参数中指定的函数强制转换,所以请根据情况进行选择。
DateField
¶DateField
(**kwargs)[source]¶DateInput
None
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
¶DateTimeField
(**kwargs)[source]¶DateTimeInput
None
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
¶DecimalField
(**kwargs)[source]¶Field.localize
是False
时为NumberInput
,否则为TextInput
。None
decimal
。max_whole_digits
, max_digits
, max_decimal_places
, max_value
, invalid
, required
, min_value
%(limit_value)s
和min_value
错误信息可能包含max_value
,它们将被真正的限制值替换。
类似地,max_whole_digits
、max_decimal_places
和 max_digits
错误消息可能包含%(max)s
。
接收四个可选的参数:
max_value
¶min_value
¶它们控制字段中允许的值的范围,应该以decimal.Decimal
值给出。
max_digits
¶值允许的最大位数(小数点之前和之后的数字总共的位数,前导的零将被删除)。
decimal_places
¶允许的最大小数位。
DurationField
¶DurationField
(**kwargs)[source]¶TextInput
None
timedelta
。timedelta
。required
, invalid
.接收任何可以被parse_duration()
理解的格式。
EmailField
¶EmailField
(**kwargs)[source]¶EmailInput
''
(一个空字符串)required
, invalid
具有两个可选的参数用于验证,max_length
和min_length
。
如果提供,这两个参数将确保字符串的最大和最小长度。
FileField
¶FileField
(**kwargs)[source]¶ClearableFileInput
None
UploadedFile
对象,它封装文件内容和文件名为一个单独的对象。missing
, invalid
, required
, empty
, max_length
具有两个可选的参数用于验证,max_length
和 allow_empty_file
。 如果提供,这两个参数确保文件名的最大长度,而且即使文件内容为空时验证也会成功。
若要了解UploadedFile
对象的更多内容,参见file uploads
documentation。
当你在表单中使用FileField
时,必须要记住bind the file data to the form。
max_length
错误信息表示文件名的长度。 在错误信息中,%(max)d
将替换为文件的最大长度,%(length)d
将替换为当前文件名的长度。
FilePathField
¶FilePathField
(**kwargs)[source]¶Select
None
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
¶FloatField
(**kwargs)[source]¶Field.localize
是False
时为NumberInput
,否则为TextInput
。None
float()
函数一样,允许前导和尾随的空白符。max_value
, invalid
, required
, min_value
接收两个可选的参数用于验证,max_value
和min_value
。
它们控制字段中允许的值的范围。
ImageField
¶ImageField
(**kwargs)[source]¶ClearableFileInput
None
UploadedFile
对象,它封装文件内容和文件名为一个单独的对象。missing
, invalid
, required
, empty
, invalid_image
使用ImageField
需要安装Pillow并支持您使用的图像格式。 如果在上传图片时遇到损坏 图像
错误,通常意味着Pillow不了解其格式。 要解决这个问题,请安装相应的库并重新安装Pillow。
在表单上使用ImageField
时,您还必须记住bind the file data to the form。
在字段清理和验证后,UploadedFile
对象将有一个额外的image
属性,包含Pillow 图像实例,用于检查文件是一个有效的图像。 另外,如果Pillow可以确定,UploadedFile.content_type
将会更新图像的内容类型,否则将被设置为None
。
IntegerField
¶IntegerField
(**kwargs)[source]¶Field.localize
是False
时为NumberInput
,否则为TextInput
。None
int()
函数。max_value
, invalid
, required
, min_value
%(limit_value)s
和min_value
错误信息可能包含max_value
,它们将被真正的限制值替换。
采用两个可选参数进行验证:
max_value
¶min_value
¶它们控制字段中允许的值的范围。
GenericIPAddressField
¶GenericIPAddressField
(**kwargs)[source]¶包含IPv4或IPv6地址的字段。
TextInput
''
(一个空字符串)required
, invalid
IPv6地址规范化遵循 RFC 4291#section-2.2第2.2节,包括使用该段第3段中建议的IPv4格式,如::ffff:192.0.2.0
例如,::ffff:0a0a:0a0a
将被标准化为2001::1
和2001:0::0:01
::ffff:10.10.10.10
。 所有字符都转换为小写。
有两个可选参数:
protocol
¶限制指定协议的有效输入。
接受的值为IPv6
(默认值),IPv4
或both
。 匹配不区分大小写。
unpack_ipv4
¶解开IPv4映射地址,例如::ffff:192.0.2.1
。
如果启用此选项,则该地址将解包到192.0.2.1
。 默认为禁用。 只能在protocol
设置为'both'
时使用。
MultipleChoiceField
¶MultipleChoiceField
(**kwargs)[source]¶SelectMultiple
[]
(一个空列表)invalid_list
, invalid_choice
, required
invalid_choice
错误消息可能包含%(value)s
,它将被选择的选项替换掉。
对于choices
,需要一个额外的必需参数ChoiceField
。
TypedMultipleChoiceField
¶TypedMultipleChoiceField
(**kwargs)[source]¶就像MultipleChoiceField
,除了TypedMultipleChoiceField
需要两个额外的参数,coerce
和empty_value
。
SelectMultiple
empty_value
coerce
参数提供的类型值列表。required
, invalid_choice
invalid_choice
错误消息可能包含%(value)s
,它将被选择的选项替换掉。
对于TypedChoiceField
,需要两个额外的参数empty_value
和coerce
。
NullBooleanField
¶NullBooleanField
(**kwargs)[source]¶NullBooleanSelect
None
None
, False
或True
值。ValidationError
)。RegexField
¶SlugField
¶TimeField
¶URLField
¶Field
类¶ComboField
¶ComboField
(**kwargs)[source]¶TextInput
''
(一个空字符串)ComboField
的参数的每个字段验证给定值。required
, invalid
接收一个额外的必选参数:
fields
¶应用于验证字段值的字段列表(按提供它们的顺序)。
>>> from django.forms import ComboField
>>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
>>> f.clean('[email protected]')
'[email protected]'
>>> f.clean('[email protected]')
Traceback (most recent call last):
...
ValidationError: ['Ensure this value has at most 20 characters (it has 28).']
MultiValueField
¶MultiValueField
(fields=(), **kwargs)[source]¶TextInput
''
(一个空字符串)compress
方法返回的类型。MultiValueField
的参数的每个字段验证给定值。incomplete
, invalid
, required
聚合共同产生单个值的多个字段的逻辑。
此字段是抽象的,必须是子类。 与单值字段相反,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)[source]¶获取有效值的列表,并在单个值中返回这些值的“压缩”版本。 例如,SplitDateTimeField
是将时间字段和日期字段合并为datetime
对象的子类。
此方法必须在子类中实现。
SplitDateTimeField
¶SplitDateTimeField
(**kwargs)[source]¶SplitDateTimeWidget
None
datetime.datetime
对象。datetime.datetime
或以特定日期时间格式格式化的字符串。invalid_date
, invalid
, required
, invalid_time
有两个可选参数:
input_date_formats
¶一个格式的列表,用于转换一个字符串为datetime.date
对象。
如果未提供input_date_formats
参数,则会使用DateField
的默认输入格式。
input_time_formats
¶用于尝试将字符串转换为有效的datetime.time
对象的格式列表。
如果未提供input_time_formats
参数,则使用TimeField
的默认输入格式。
两个字段可用于表示模型之间的关系:ModelChoiceField
和ModelMultipleChoiceField
。 这两个字段都需要单个queryset
参数,用于创建字段的选择。 在表单验证时,这些字段将把一个模型对象(在cleaned_data
的情况下)或多个模型对象(在ModelMultipleChoiceField
的情况下)放置到ModelChoiceField
表单的字典。
对于更复杂的用法,可以在声明表单字段时指定__init__()
,然后在窗体的queryset
方法中填充queryset=None
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
¶ModelChoiceField
(**kwargs)[source]¶Select
None
required
, invalid_choice
可以选择一个单独的模型对像,适用于表示一个外键字段。 ModelChoiceField
默认widet不适用选择数量很大的情况, 在大于100项时应该避免使用它。
需要单个参数:
queryset
¶模型对象的QuerySet
,从中导出该字段的选项,并用于验证用户的选择。 在表单呈现时进行评估。
ModelChoiceField
也有两个可选参数:
empty_label
¶默认情况下,<select>
使用的ModelChoiceField
小部件将在列表顶部有一个空选项。 您可以使用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__
)的方法来生成字段用于该字段选择的对象的字符串表示;提供定制表示,子类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
¶ModelMultipleChoiceField
(**kwargs)[source]¶SelectMultiple
QuerySet
(self.queryset.none())QuerySet
。invalid_choice
, list
, required
, invalid_pk_value
invalid_pk_value
消息可以包含%(value)s
并且invalid_choice
消息可以包含%(pk)s
其将被适当的值代替。
允许选择适合于表示多对多关系的一个或多个模型对象。 与ModelChoiceField
一样,您可以使用label_from_instance
自定义对象表示。
需要单个参数:
queryset
¶接收一个可选的参数:
to_field_name
¶如果内建的Field
不能满足你的需求,你可以很容易地创建自定义的Field
。 你需要创建django.forms.Field
的一个子类。 它只要求实现一个help_text
方法和接收上面核心参数的initial
方法(widget
, required
, __init__()
, clean()
, label
)。
您还可以通过覆盖get_bound_field()
来自定义访问字段的方式。
2017年9月6日