django关于form组件

利用form组件可以很方便的实现对网页表单数据的管理及响应;
1.Form Fields
(1)BooleanField

class BooleanField(**kwargs)
• Default widget: CheckboxInput
• Empty value: False
• Normalizes to: A Python True or False value.
• Validates that the value is True (e.g. the check box is checked) if the field has required=True.
• Error message keys: required
Note: Since all Field subclasses have required=True by default, the validation condition here is important. If you want to include a boolean in your form that can be either True or False (e.g. a checked or unchecked checkbox), you must remember to pass in required=False when creating the BooleanField.

默认插件:checkboxInput;
空值: False;
规范化为python的True或False值;
有效性:当值为True,也即checkbox被选中时;
错误信息的键:required;
注意: 默认required为True, 所以如果想接收False值,必须将此参数设为False;

(2)CharField

class CharField(**kwargs)
• Default widget: TextInput
• Empty value: Whatever you’ve given as empty_value.
• Normalizes to: A string.
• Uses MaxLengthValidator and MinLengthValidator if max_length and min_length are
provided. Otherwise, all inputs are valid.
• Error message keys: required, max_length, min_length
Has three optional arguments for validation:
max_length
min_length
If provided, these arguments ensure that the string is at most or at least the given length. strip
If True (default), the value will be stripped of leading and trailing whitespace.
empty_value
The value to use to represent “empty”. Defaults to an empty string.

默认插件:TextInput;
空值: 根据empty_value参数确定;
规范化为:python的字符串;
有效性:判断是否符合最大长度和最小长度;
错误信息的键:required,max_length, min_length

有4个可选参数:
max_length,
min_length,
strip:默认为True, 将会把输入值去除前后的空白;
empty_value:当输入为空时的替代值,默认为空字符串;

(3)ChoiceField

class ChoiceField(**kwargs)
• Default widget: Select
• Empty value: ‘’ (an empty string)
• Normalizes to: A string.
• Validates that the given value exists in the list of choices.
• Error message keys: required, invalid_choice
The invalid_choice error message may contain %(value)s, which will be replaced with the selected choice.
Takes one extra argument:
choices
Either an iterable (e.g., a list or tuple) 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 choices argument 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.

默认插件:Select;
空值: 空字符串"";
规范化为:python的字符串;
有效性:判断给出的值是否在choices中;
错误信息的键:required,invalid_choice??

额外参数:choices: 一个由2元素元组的可迭代对象;也可以是返回这样一个可迭代对象的可调用对象,这样的话每当表的字段初始化时都会调用一次该对象;默认为一个空列表;

关于choices:

An iterable (e.g., a list or tuple) consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) …]) to use as choices for this field. If choices are given, they’re enforced by model validation and the default form widget will be a select box with these choices instead of the standard text field.

如果给出choices参数, 则默认组件由text改为select box;

Note that choices can be any iterable object – not necessarily a list or tuple. This lets you construct choices dynamically. But if you find yourself hacking choices to be dynamic, you’re probably better off using a proper database table with a ForeignKey. choices is meant for static data that doesn’t change much, if ever.

choices参数可以是任何可迭代对象,而不只是列表或元组;这允许我们动态更新数据;

Unless blank=False is set on the field along with a default then a label containing “---------” will be rendered with the select box. To override this behavior, add a tuple to choices containing None; e.g. (None, ‘Your String For Display’). Alternatively, you can use an empty string instead of None where this makes sense - such as on a CharField

除非blank(required)参数设为False, 并且给出默认值,否则select box会包含选项"-------";
如果你想覆盖这种行为, 可以在choice中包括(None, “something”)或者使用空字符串代替None;

(4)TypedChoiceField

class TypedChoiceField(**kwargs)
Just like a ChoiceField, except TypedChoiceField takes two extra arguments, coerce and empty_value.
• Default widget: Select
• Empty value: Whatever you’ve given as empty_value.
• Normalizes to: A value of the type provided by the coerce argument.
• Validates that the given value exists in the list of choices and can be coerced.
• Error message keys: required, invalid_choice
Takes extra arguments:
coerce
A function that takes one argument and returns a coerced value. Examples include the built-in int, float, bool and 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 in choices.
empty_value
The value to use to represent “empty.” Defaults to the empty string; None is another common choice here. Note that this value will not be coerced by the function given in the coerce argument, so choose it accordingly.

和ChoiceField大致相同,但还有两个默认参数;
默认插件:Select;
空值: 根据empyt_value参数确定;
规范化为:根据coerce参数确定的类型;
有效性:判断给出的值是否在choices中,以及是否可以被coerce转换;
错误信息的键:required,invalid_choice??

参数coerce:
输入一个参数并返回一个转化值的函数;默认为identity函数;注意该转化发生在输入数据校验以后,所以可能转化后可能出现choices中不存在的值;

参数empty_value:
输入为空时的值,默认为空字符串, None也是一种选择.注意该值并不会被coerce转化;

(5)DateField

class DateField(**kwargs)
• Default widget: DateInput
• Empty value: None
• Normalizes to: A Python datetime.date object.
• Validates that the given value is either a datetime.date, datetime.datetime or string formatted in a particular date format.
• Error message keys: required, invalid
Takes one optional argument:
input_formats
A list of formats used to attempt to convert a string to a valid datetime.date object.
If no input_formats argument is provided, the default input formats are:

['%Y-%m-%d', # '2006-10-25'
'%m/%d/%Y', # '10/25/2006'
'%m/%d/%y'] # '10/25/06'

默认插件:DateInput;
空值: None;
规范化为:python datetime.date对象;
有效性:判断给出的值是否为指定格式的字符串或datetime.date, datetime.datetime对象;
错误信息的键:required,invalid

额外参数input_formats:
一个用于将字符串转化为时间对象的格式的列表,默认如上;

Additionally, if you specify USE_L10N=False in your settings, the following will also be included in the
default input formats:
[’%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’

(6)DateTimeField

class DateTimeField(**kwargs)
• Default widget: DateTimeInput
• Empty value: None
• Normalizes to: A Python datetime.datetime object.
• Validates that the given value is either a datetime.datetime, datetime.date or string formatted in a particular datetime format.
• Error message keys: required, invalid
Takes one optional argument:
input_formats
A list of formats used to attempt to convert a string to a valid datetime.datetime object.
If no input_formats argument is provided, the default input formats are:

['%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'

默认插件:DateTimeInput;
空值: None;
规范化为:python datetime.datetime对象;
有效性:判断给出的值是否为指定格式的字符串或datetime.date, datetime.datetime对象;
错误信息的键:required,invalid;

额外参数input_formats:
一个用于将字符串转化为时间对象的格式的列表,默认如上;

(7)DecimalField

class DecimalField(**kwargs)
• Default widget: NumberInput when Field.localize is False, else TextInput.
• Empty value: None
• Normalizes to: A Python decimal.
• Validates that the given value is a decimal. Uses MaxValueValidator and MinValueValidator if max_value and min_value are 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_value and min_value error messages may contain %(limit_value)s, which will be substituted by the appropriate limit. Similarly, the max_digits, max_decimal_places and max_whole_digits error messages may contain %(max)s.
Takes four optional arguments:
max_value
min_value
These control the range of values permitted in the field, and should be given as decimal.Decimal values.
max_digits
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_places
The maximum number of decimal places permitted.

默认插件:Field.localize为false时NumberInput, true时TextInput;
空值: None;
规范化为:python decimal对象;
有效性:判断给出的值是否为decimal,并且判断是否符合max_value, min_value, 前导和后缀空白将被忽略;
错误信息的键:required,invalid,max_value, min_value, max_digits,
max_decimal_places, max_whole_digits;

额外的四个参数:
max_value,
min_value:控制值的范围;
max_digits:最大位数, 即小数的总位数;
decimal_places:最大的小数位数

(8)EmailField

class EmailField(**kwargs)
• Default widget: EmailInput
• Empty value: ‘’ (an empty string)
• Normalizes to: A string.
• Uses EmailValidator to validate that the given value is a valid email address, using a moderately complex regular expression.
• Error message keys: required, invalid
Has two optional arguments for validation, max_length and min_length. If provided, these arguments ensure that the string is at most or at least the given length.

默认插件:EmailInput;
空值: 空字符串;
规范化为:字符串;
有效性:判断给出的值是否为有效的邮箱地址,使用正则表达式;
错误信息的键:required,invalid;

额外的2个参数:
max_length, min_length;

(9)FileField

class FileField(**kwargs)
• Default widget: ClearableFileInput
• Empty value: None
• Normalizes to: An UploadedFile object that wraps the file content and file name into a single object.
• 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_length and allow_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.
To learn more about the UploadedFile object, see the file uploads documentation.
When you use a FileField in a form, you must also remember to bind the file data to the form.
The max_length error refers to the length of the filename. In the error message for that key, %(max)d will be replaced with the maximum filename length and %(length)d will be replaced with the current filename length.

默认插件:ClearableFileInput;
空值: None;
规范化为:UploadedFile对象,封装了文件的内容和文件名;
有效性:判断是否为空文件;
错误信息的键:required,invalid,missing, empty, max_length;

额外的两个参数:
max_length:规定文件名的最大长度,就算是空文件,只要文件名满足条件也会通过验证;
allow_empty_file:是否允许空文件;

注意使用该字段是要绑定form;(enctype=“multipart/form-data”)

(10)FloatField

class FloatField(**kwargs)
• Default widget: NumberInput when Field.localize is False, else TextInput.
• Empty value: None
• Normalizes to: A Python float.
• Validates that the given value is a float. Uses MaxValueValidator and MinValueValidator if max_value and min_value are provided. Leading and trailing whitespace is allowed, as in Python’s float() function.
• Error message keys: required, invalid, max_value, min_value
Takes two optional arguments for validation, max_value and min_value. These control the range of values permitted in the field.

默认插件:Field.localize为false时NumberInput, true时TextInput;
空值: None;
规范化为:python 浮点数;
有效性:判断给出的值是否为float,并且判断是否符合max_value, min_value, 前导和后缀空白是允许的,就像float()函数里一样;
错误信息的键:required,invalid,max_value, min_value;

额外的2个参数:
max_value,
min_value:控制值的范围;

(11)ImageField

class ImageField(**kwargs)
• Default widget: ClearableFileInput
• Empty value: None
• Normalizes to: An UploadedFile object that wraps the file content and file name into a single object.
• Validates that file data has been bound to the form. Also uses FileExtensionValidator to validate that the file extension is supported by Pillow.
• Error message keys: required, invalid, missing, empty, invalid_image
Using an ImageField requires that Pillow is installed with support for the image formats you use. If you encounter a corrupt image error 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 ImageField on a form, you must also remember to bind the file data to the form.
After the field has been cleaned and validated, the UploadedFile object will have an additional image attribute containing the Pillow Image instance used to check if the file was a valid image. Also, UploadedFile. content_type will be updated with the image’s content type if Pillow can determine it, otherwise it will be set to None.

默认插件:ClearableFileInput;
空值: None;
规范化为:UploadedFile对象,封装了文件的内容和文件名;
有效性:判断是否为绑定到了form上, 并且判断是否被pillow支持;
错误信息的键:required,invalid,missing, empty, invalid_image;

需要安装pillow以获取支持;如果遇到图片损坏的情况,通常意味着pillow不认识你的格式,安装合适的库或者重装pillow;

注意使用该字段是要绑定form;(enctype=“multipart/form-data”);
当图片以进行过校验,UploadedFile对象将会有一个额外的image属性, 包含pillow image实例,用于检查文件是否为有效的图片;同时UploadedFile.content_type也会更新;

(12)IntegerField

class IntegerField(**kwargs)
• Default widget: NumberInput when Field.localize is False, else TextInput.
• Empty value: None
• Normalizes to: A Python integer.
• Validates that the given value is an integer. Uses MaxValueValidator and MinValueValidator if max_value and min_value are provided. Leading and trailing whitespace is allowed, as in Python’s int() function.
• Error message keys: required, invalid, max_value, min_value
The max_value and min_value error messages may contain %(limit_value)s, which will be substituted by the appropriate limit.
Takes two optional arguments for validation:
max_value
min_value
These control the range of values permitted in the field.

默认插件:Field.localize为false时NumberInput, true时TextInput;
空值: None;
规范化为:python 整数;
有效性:判断给出的值是否为整数,并且判断是否符合max_value, min_value, 前导和后缀空白是允许的, 就像int()函数里一样;
错误信息的键:required,invalid,max_value, min_value;

额外的2个参数:
max_value,
min_value:控制值的范围;

(13)GenericIPAddressField

class GenericIPAddressField(**kwargs)
A field containing either an IPv4 or an IPv6 address.
• Default widget: TextInput
• Empty value: ‘’ (an empty string)
• Normalizes to: A string. IPv6 addresses are normalized as described below.
• Validates that the given value is a valid IP address.
• Error message keys: required, invalid
The IPv6 address normalization follows RFC 4291#section-2.2 section 2.2, including using the IPv4 format suggested in paragraph 3 of that section, like ::ffff:192.0.2.0. For example, 2001:0::0:01 would be normalized to 2001::1, and ::ffff:0a0a:0a0a to ::ffff:10.10.10.10. All characters are converted to lowercase.
Takes two optional arguments:
protocol
Limits valid inputs to the specified protocol. Accepted values are both (default), IPv4 or IPv6. Matching is case insensitive.
unpack_ipv4
Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to ‘both’.

填写IPV4或IPV6地址的字段;
默认插件:TextInput;
空值: 空字符串;
规范化为:字符串, IPV6地址见下方;
有效性:判断给出的值是否为有效的IP地址;
错误信息的键:required,invalid;

IPv6地址规范化遵循RFC 4291#section-2.2第2.2节;

额外的2个参数:
protocol: 限制有效输入的指定协议,默认为both, 可以为IPV4或IPV6, 区分大小写;
unpack_ipv4: 将::ffff:192.0.2.1格式转变为192.0.2.1, 默认disabled; 只能在protocol为both时使用;

(14)MultipleChoiceField

class MultipleChoiceField(**kwargs)
• Default widget: SelectMultiple
• Empty value: [] (an empty list)
• 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_choice error message may contain %(value)s, which will be replaced with the selected choice.
Takes one extra required argument, choices, as for ChoiceField.

默认插件:SelectMultiple;
空值: []空列表;
规范化为:字符串的列表;
有效性:判断给出列表中的每个值是否在choices列表中;
错误信息的键:required,invalid_choice, invalid_list;

额外参数:choices:和ChoiceField相同;

(15)TypedMultipleChoiceField

class TypedMultipleChoiceField(**kwargs)
Just like a MultipleChoiceField, except TypedMultipleChoiceField takes two extra arguments, coerce and empty_value.
• Default widget: SelectMultiple
• Empty value: Whatever you’ve given as empty_value
• Normalizes to: A list of values of the type provided by the coerce argument.
• Validates that the given values exists in the list of choices and can be coerced.
• Error message keys: required, invalid_choice
The invalid_choice error message may contain %(value)s, which will be replaced with the selected choice.
Takes two extra arguments, coerce and empty_value, as for TypedChoiceField.

默认插件:SelectMultiple;
空值: empty_value中的值;
规范化为:被coerce转化后的值的列表;
有效性:判断给出列表中的每个值是否在choices列表中并且是否可转化;
错误信息的键:required,invalid_choice;

额外参数:coerce和empty_value:和TypedChoiceField相同;

(16)NullBooleanField

class NullBooleanField(**kwargs)
• Default widget: NullBooleanSelect
• Empty value: None
• Normalizes to: A Python True, False or None value.
• Validates nothing (i.e., it never raises a ValidationError).

默认插件:NullBooleanSelect;
空值: None;
规范化为:True, False, value;
错误信息的键:从来不报错;

(17)RegexField

class RegexField(**kwargs)
• Default widget: TextInput
• Empty value: ‘’ (an empty string)
• Normalizes to: A string.
• Uses RegexValidator to validate that the given value matches a certain regular expression.
• Error message keys: required, invalid
Takes one required argument:
regex
A regular expression specified either as a string or a compiled regular expression object.
Also takes max_length, min_length, and strip, which work just as they do for CharField.
strip
Defaults to False. If enabled, stripping will be applied before the regex validation.

默认插件:TextInput;
空值: 空字符串;
规范化为:字符串;
有效性:判断给出的值是否可被某个正则表达式匹配;
错误信息的键:required, invalid;

额外参数:regex:
一个正则表达式或编译后的正则表达对象;
同时还有max_length, min_length, 和strip参数, 与CharField中相同;
注意:strip参数默认为False, 如果设为True, 将在正则表达式校验前使用;

(18)SlugField

class SlugField(**kwargs)
• Default widget: TextInput
• Empty value: ‘’ (an empty string)
• Normalizes to: A string.
• Uses validate_slug or validate_unicode_slug to 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 SlugField in forms.
Takes an optional parameter:
allow_unicode
A boolean instructing the field to accept Unicode letters in addition to ASCII letters. Defaults to False.

默认插件:TextInput;
空值: 空字符串;
规范化为:字符串;
有效性:判断给出的值是否只包含字母,数字,下划线和连字符;
错误信息的键:required, invalid;

This field is intended for use in representing a model SlugField in forms.???

额外的参数:allow_unicode:
一个布尔值,用于指明该字段除了接受ASCII字符还接受Unicode;

(19)TimeField

class TimeField(**kwargs)
• Default widget: TimeInput
• Empty value: None
• Normalizes to: A Python datetime.time object.
• Validates that the given value is either a datetime.time or string formatted in a particular time format.
• Error message keys: required, invalid
Takes one optional argument:
input_formats
A list of formats used to attempt to convert a string to a valid datetime.time object.
If no input_formats argument is provided, the default input formats are:

'%H:%M:%S', # '14:30:59'
'%H:%M', # '14:30'

默认插件:TimeInput;
空值: None;
规范化为:datetime.time对象;
有效性:判断给出的值是否为给定格式的字符串或datetime.time格式;
错误信息的键:required, invalid;

额外参数:input_formats
默认如上;

(20)URLField

class URLField(**kwargs)
• Default widget: URLInput
• Empty value: ‘’ (an empty string)
• Normalizes to: A string.
• Uses URLValidator to validate that the given value is a valid URL.
• Error message keys: required, invalid
Takes the following optional arguments:
max_length
min_length
These are the same as CharField.max_length and CharField.min_length.

默认插件:URLInput;
空值: 空字符串;
规范化为:字符串;
有效性:判断给出的值是否为有效的URL;
错误信息的键:required, invalid;

额外的参数:
max_length, min_length

(21)UUIDField

class UUIDField(**kwargs)
• Default widget: TextInput
• Empty value: ‘’ (an empty string)
• Normalizes to: A UUID object.
• Error message keys: required, invalid
This field will accept any string format accepted as the hex argument to the UUID constructor.

默认插件:URLInput;
空值: 空字符串;
规范化为:UUID 对象;
错误信息的键:required, invalid;

(22)ComboField

class ComboField(**kwargs)
• Default widget: TextInput
• Empty value: ‘’ (an empty string)
• Normalizes to: A string.
• Validates the given value against each of the fields specified as an argument to the ComboField.
• Error message keys: required, invalid
Takes one extra required argument:
fields
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).']

默认插件:TextInput;
空值: 空字符串;
规范化为:字符串;
有效性:判断给出的值是否符合参数中指定的所有字段的规则;
错误信息的键:required, invalid;

额外参数:fields:
字段的列表,用于验证字段的值, 按给定顺序进行验证,上例;

(23)剩余字段待补充…

2.Fields which handle relationships处理莫得了间关系的字段:
(1)概述

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

共有两个字段ModelChoiceField和ModelMultipleChoiceField;
这两个字段要求一个queryset参数,用于创建字段的choices;在表单验证时,这些字段会将一个或几个model对象放入 cleaned_data字典;
更复杂的应用, 可以将queryset设为None,然后将queryset添加到__ init__方法中;

(2)ModelChoiceField

class ModelChoiceField(**kwargs)
• Defaultwidget: Select
• Empty value: None
• Normalizes to: A model instance.
• 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 ModelChoiceField becomes impractical when the number of entries increases. You should avoid using it for more than 100 items.
A single argument is required:
queryset
A QuerySet of 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.
ModelChoiceField also takes two optional arguments:
empty_label
By default the < select> widget used by ModelChoiceField will have an empty choice at the top of the list. You can change the text of this label (which is “---------” by default) with the empty_label attribute, or you can disable the empty label entirely by setting empty_label to None:

#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 ModelChoiceField is required and has a default initial value, no empty choice is created (regardless of the value of empty_label).

默认插件:Select;
空值: None;
规范化为:模型对象;
有效性:判断给出的id是否存在于queryset中;
错误信息的键:required, invalid_choice;

允许选择模型的单个对象, 尤其适合表示外键; 注意当对象数量增加时默认插件不再可靠, 你应该避免它超过100个条目;

一个必须参数:
queryset:模型对象的QuerySet, 用于作为字段的选项并用于验证用户的选择; 当表单渲染时计算;

两个可选参数:
1)empty_label:用于设置空选项的格式,默认为"--------", 可以通过设置该参数为None来取消它;注意:如果设置了required为True并且有默认值, 该参数无效;

2)to_field_name

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, subclass ModelChoiceField and override label_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

该参数指定了用于choices的value值的字段, 要确保该字段是唯一的, 否则选择的值将会匹配到多个对象, 默认情况下该参数为None, 会使用模型的主键作为value值, 见上例;

模型的__ str__方法将会被调用, 用于choices中的显示; 如果想定制显示内容, 可以使用它的子类, 然后覆盖label_from_instance方法, 该方法传入一个模型对象然后返回字符串,见上例;

(3)ModelMultipleChoiceField

class ModelMultipleChoiceField(**kwargs)
• Default widget: SelectMultiple
• Empty value: An empty QuerySet (self.queryset.none())
• Normalizes to: A QuerySet of 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_choice message may contain %(value)s and the invalid_pk_value message 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 use label_from_instance to customize the object representations.
A single argument is required:
queryset
Same as ModelChoiceField.queryset.
Takes one optional argument:
to_field_name
Same as ModelChoiceField.to_field_name.

默认插件:SelectMultiple;
空值: 空的QuerySet;
规范化为:QuerySet;
有效性:判断给出的列表中的每个id是否存在于queryset中;
错误信息的键:required, invalid_choice, list, invalid_pk_value;

可以选择一个或多个模型对象, 适用于表示多对多关系; 和ModelChoiceField一样,可以使用label_from_instance方法来定制展示的内容;

一个必须参数:
queryset;

一个可选参数:
to_field_name;

3.form实例的方法
(1)Form.is_bound
查看是否为绑定表单:

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

#Note that passing an empty dictionary creates a bound form with empty data:
>>> f = ContactForm({})
>>> f.is_bound
True

(2)Form.clean()

Implement a clean() method on your Form when you must add custom validation for fields that are interdependent.

当必须为相互依赖的字段添加自定义验证时使用此方法;

(3)Form.is_valid()

The primary task of a Form object is to validate data. With a bound Form instance, call the is_valid() method to run validation and return a boolean designating whether the data was valid:

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

检查数据是否有效;

(4)Form.errors

Access the errors attribute to get a dictionary of error messages:

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

In this dictionary, the keys are the field names, and the values are lists of strings representing the error messages. The error messages are stored in lists because a field can have multiple error messages.

You can access errors without having to call is_valid() first. The form’s data will be validated the first time either you call is_valid() or access errors.
The validation routines will only get called once, regardless of how many times you access errors or call is_valid(). This means that if validation has side effects, those side effects will only be triggered once.

获取表单错误信息的字典,如上; 不必先调用is_valid()方法就可以获取错误信息,因为访问error属性和is_valid()方法都会验证数据;
验证数据的行为只会发生一次, 无论你调用多少次该属性;

(5)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. It’s trivial to do so using a JavaScript library like jQuery - simply use $(el).text(errorText) rather than .html().
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.

将错误信息序列化为JSON字符串并返回; 默认情况下输出结果并不会进行转义, 如果你想在Ajax请求中处理响应并在页面中插入错误信息, 你会想要转义结果以避免跨站攻击,直接调用$(el).text(errorText)就可以;
如果你想转义输出结果, 将参数escape_html设为True就可以;

(6)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.
The field argument is the name of the field to which the errors should be added. If its value is None the error will be treated as a non-field error as returned by Form.non_field_errors().
The error argument can be a simple string, or preferably an instance of ValidationError. See Raising ValidationError for best practices when defining form errors.
Note that Form.add_error() automatically removes the relevant field from cleaned_data.

此方法允许从form.clean()方法或表单外部(例如视图函数)向特定字段中添加错误;
field参数是表单中的字段名,如果设为None,则会被视为非字段错误(在Form.non_field_errors() ) 方法中;
error参数可以是字符串或者ValidationError的实例;
注意此方法自动从cleaned_data中移除相关字段;

(7)Form.has_error(field, code=None)

This method returns a boolean designating whether a field has an error with a specific error code. If code is None,
it will return True if the field contains any errors at all.
To check for non-field errors use NON_FIELD_ERRORS as the field parameter.

返回布尔值,指明该字段是否有特定的错误信息, 如果code参数是None, 则检查是否包含任何错误信息; 将field参数设为NON_FIELD_ERRORS来检查非字段错误;

(8)Form.non_field_errors()

This method returns the list of errors from Form.errors that aren’t associated with a particular field. This includes ValidationErrors that are raised in Form.clean() and errors added using Form.add_error(None, “…”).

返回非字段错误信息的列表,包括Form.clean()方法抛出的ValidationErrors和Form.add_error(None, “…”) 添加的错误;

(9)Form.initial

Use initial to declare the initial value of form fields at runtime. For example, you might want to fill in a username field with the username of the current session.
To accomplish this, use the initial argument to a Form. This argument, if given, should be a dictionary mapping field names to initial values. Only include the fields for which you’re specifying an initial value; it’s not necessary to include every field in your form. For example:

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

These values are only displayed for unbound forms, and they’re not used as fallback values if a particular value isn’t provided.
If a Field defines initial and you include initial when instantiating the Form, then the latter initial will have precedence. In this example, initial is provided both at the field level and at the form instance level, and the latter gets precedence:

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

使用initial属性来指定表单字段的初始值; 该参数应该是一个字典, 映射了字段名和初始值;不必指明每个字段;
这些值只是用于非绑定表单, 如果没有给出特定值, 将不会用做回退值;
如果字段单独定义了初始值,而你又在初始化表单时规定了初始值, 那后者将优先使用.见上例;

(10)Form.get_initial_for_field(field, field_name)

Use get_initial_for_field() to retrieve initial data for a form field. It retrieves data from Form.initial and Field.initial, in that order, and evaluates any callable initial values.

使用此方法获得表单字段的初始值

(11)Form.has_changed()

Use the has_changed() method on your Form when you need to check if the form data has been changed from the initial data.

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

When the form is submitted, we reconstruct it and provide the original data so that the comparison can be done:

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

has_changed() will be True if the data from request.POST differs from what was provided in initial or False otherwise. The result is computed by calling Field.has_changed() for each field in the form.

此方法用于检测表单数据相对于初始值是否已改变;当表单通过submit提交,可以使用上面的方式判断;

(12)Form.changed_data

The changed_data attribute returns a list of the names of the fields whose values in the form’s bound data (usually request.POST) differ from what was provided in initial. It returns an empty list if no data differs.

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

此属性返回数据改变的字段的名称的列表,如果数据未改变则返回空列表;见上例;

(13)Form.fields

You can access the fields of Form instance from its fields attribute:

>>> 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 of Form instance to change the way it is presented in the form:
>>> f.as_table().split('\n')[0]
'<tr><th>Name:</th><td><input name="name" type="text" value="instance" required></td>
˓→</tr>'
>>> f.fields['name'].label = "Username"
>>> f.as_table().split('\n')[0]
'<tr><th>Username:</th><td><input name="name" type="text" value="instance" required></
˓→td></tr>'

#Beware not to alter the base_fields attribute because this modification will influence all subsequent ContactForm instances within the same Python process:
>>> f.base_fields['name'].label = "Username"
>>> another_f = CommentForm(auto_id=False)
>>> another_f.as_table().split('\n')[0]
'<tr><th>Username:</th><td><input name="name" type="text" value="class" required></td>
˓→</tr>'

该属性可以访问表单实例的字段,使用见上例, 以字典的形式访问;

(14)Form.cleaned_data

1)Each field in a Form class is responsible not only for validating data, but also for “cleaning” it – normalizing it to a consistent format. This is a nice feature, because it allows data for a particular field to be input in a variety of ways, always resulting in consistent output.
For example, DateField normalizes input into a Python datetime.date object. Regardless of whether you pass it a string in the format ‘1994-07-15’, a datetime.date object, or a number of other formats, DateField will always normalize it to a datetime.date object as long as it’s valid.
Once you’ve created a Form instance with a set of data and validated it, you can access the clean data via its cleaned_data attribute:

>>> 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'}

表单中的每个字段不仅会校验数据,还会“清洗”它, 将数据转变为统一的数据及格式;这样的好处是可以允许输入形式的多样化而输出结果都是一致的格式;
你可以通过cleaned_data属性访问清洗后的数据;

2)Note that any text-based field – such as CharField or EmailField – always cleans the input into a string. We’ll cover the encoding implications later in this document.
If your data does not validate, the cleaned_data dictionary contains only the valid fields:

>>> 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'}

所有基于文本的字段,例如CharField,会把数据规范化为字符串, 另外,如果数据没有通过验证,那它将不会被放入cleaned_data的字典中;

3)cleaned_data will always only contain a key for fields defined in the Form, even if you pass extra data when you define the Form. In this example, we pass a bunch of extra fields to the ContactForm constructor, but cleaned_data contains only the form’s fields:

>>> 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'}

cleaned_data只包括表单中的字段的值,就算传入额外的数据,也不会出现在cleaned_data中;

4)When the Form is valid, cleaned_data will include a key and value for all its fields, even if the data didn’t include a value for some optional fields. In this example, the data dictionary doesn’t include a value for the nick_name field, but cleaned_data includes it, with an empty value:

>>> 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'}

In this above example, the cleaned_data value for nick_name is set to an empty string, because nick_name is CharField, and CharFields treat empty values as an empty string. Each field type knows what its “blank” value is – e.g., for DateField, it’s None instead of the empty string. For full details on each field’s behavior in this case, see the “Empty value” note for each field in the “Built-in Field classes” section below.

当表单通过验证,cleaned_data将会包含所有字段的key,和value,就算某个字段没有值,也会为它补上空值;见上例;

(15)生成HTML

This default output is a two-column HTML table, with a < tr> for each field. Notice the following:
• For flexibility, the output does not include the < table> and < /table> tags, nor does it include the < form> and < /form> tags or an < input type=“submit”> tag. It’s your job to do that.
• Each field type has a default HTML representation. CharField is represented by an < input type=“text”> and EmailField by an < input type=“email”>. BooleanField is represented by an < input type=“checkbox”>. Note these are merely sensible defaults; you can specify which HTML to use for a given field by using widgets, which we’ll explain shortly.
• The HTML name for each tag is taken directly from its attribute name in the ContactForm class.
• The text label for each field – e.g. ‘Subject:’, ‘Message:’ and ‘Cc myself:’ is generated from the field name by converting all underscores to spaces and upper-casing the first letter. Again, note these are merely sensible defaults; you can also specify labels manually.
• Each text label is surrounded in an HTML < label> tag, which points to the appropriate form field via its id. Its id, in turn, is generated by prepending ‘id_’ to the field name. The id attributes and < label> tags are included in the output by default, to follow best practices, but you can change that behavior.
• The output uses HTML5 syntax, targeting . For example, it uses boolean attributes such as checked rather than the XHTML style of checked=‘checked’.

(16)生成html的格式:

Although < table> output is the default output style when you print a form, other output styles are available. Each style is available as a method on a form object, and each rendering method returns a string.

默认生成table标签的元素;但也可以通过以下几个方法改变输入的格式;

1)as_p()
Form.as_p()

as_p() renders the form as a series of < p> tags, with each < p> containing one field:

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

2)as_ul()
Form.as_ul()

as_ul() renders the form as a series of < li> tags, with each < li> containing one field. It does not include the < ul> or < /ul>, so that you can specify any HTML attributes on the < ul> for flexibility:

>>>> f.as_ul()
>>> f = ContactForm()
'<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>

此方法将表单渲染为一系列的li标签, 每个标签包含一个字段, 但不包含ul标签,需要自己指定;

3)Form.as_table()

Finally, as_table() outputs the form as an HTML < table>. This is exactly the same as print. In fact, when you print a form object, it calls its as_table() method behind the scenes:

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

此方法将表单渲染为table标签的元素,也是默认的方式, 和直接打印效果相同,实际上,当你打印一个表单对象时, 它在后台调用as_table方法;

(17)设置css样式
Form.error_css_class
Form.required_css_class

It’s pretty common to style form rows and fields that are required or have errors. For example, you might want to present required form rows in bold and highlight errors in red.
The Form class has a couple of hooks you can use to add class attributes to required rows or to rows with errors: simply set the Form.error_css_class and/or Form.required_css_class attributes:

from django import forms
class ContactForm(forms.Form):
error_css_class = 'error'
required_css_class = 'required'
#... and the rest of your fields here

Once you’ve done that, rows will be given “error” and/or “required” classes, as needed. The HTML will look something like:

>>> 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'].label_tag(attrs={'class': 'foo'})
<label for="id_subject" class="foo required">Subject:</label>

可以使用如上2个属性给生成的标签添加class类;

(18)Form.auto_id

By default, the form rendering methods include:
• HTML id attributes on the form elements.
• The corresponding < label> tags around the labels. An HTML < label> tag designates which label text is associated with which form element. This small enhancement makes forms more usable and more accessible to assistive devices. It’s always a good idea to use < label> tags.
The id attribute values are generated by prepending id_ to the form field names. This behavior is configurable, though, if you want to change the id convention or remove HTML id attributes and < label> tags entirely.
Use the auto_id argument to the Form constructor to control the id and label behavior. This argument must be True, False or a string.

默认情况下,表单渲染会包括如下内容:
1)表单元素的HTML id属性;
2)标签周围将生成相应的lable标签, 一个label标签将指定哪个标签文本和哪个表单元素相关联;这种增强使得表单更加易用, 辅助设备也更加容易使用;
id属性是通过使用id_ 后面加表单字段名称生成的, 你也可以配置这种行为, 更改id生成或直接移除id属性和label标签;

使用auto_id属性就可以实现对id属性和label标签的配置, 这个属性必须是True, False, 或一个字符串;
1)如果是False, 将不会包括label标签和id属性;

If auto_id is False, then the form output will not include < label> tags nor id attributes:

>>> f = ContactForm(auto_id=False)
>>> print(f.as_table())
<tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" required></
˓→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></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></li>
<li>Message: <input type="text" name="message" required></li>
<li>Sender: <input type="email" name="sender" required></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></p>
<p>Message: <input type="text" name="message" required></p>
<p>Sender: <input type="email" name="sender" required></p>
<p>Cc myself: <input type="checkbox" name="cc_myself"></p>

2)如果设为True, 则表单输出将会包含label标签并且只使用字段名作为其id;

If auto_id is set to True, then the form output will include < label> tags and will simply use the field name as its id for each form field:

>>> f = ContactForm(auto_id=True)
>>> print(f.as_table())
<tr><th><label for="subject">Subject:</label></th><td><input id="subject" type="text"
˓→name="subject" maxlength="100" required></td></tr>
<tr><th><label for="message">Message:</label></th><td><input type="text" name="message
˓→" id="message" required></td></tr>
<tr><th><label for="sender">Sender:</label></th><td><input type="email" name="sender"
˓→id="sender" required></td></tr>
<tr><th><label for="cc_myself">Cc myself:</label></th><td><input type="checkbox" name=
˓→"cc_myself" id="cc_myself"></td></tr>
>>> print(f.as_ul())
<li><label for="subject">Subject:</label> <input id="subject" type="text" name=
˓→"subject" maxlength="100" required></li>
<li><label for="message">Message:</label> <input type="text" name="message" id=
˓→"message" required></li>
<li><label for="sender">Sender:</label> <input type="email" name="sender" id="sender"
˓→required></li>
<li><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself"
˓→id="cc_myself"></li>
>>> print(f.as_p())
<p><label for="subject">Subject:</label> <input id="subject" type="text" name="subject
˓→" maxlength="100" required></p>
<p><label for="message">Message:</label> <input type="text" name="message" id="message
˓→" required></p>
<p><label for="sender">Sender:</label> <input type="email" name="sender" id="sender"
˓→required></p>
<p><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself"
˓→id="cc_myself"></p>

3)如果设为包含%s的字符串, 那输出结果将会包含label标签并基于格式字符串生成id;

If auto_id is set to a string containing the format character ‘%s’, then the form output will include < label> tags, and will generate id attributes based on the format string. For example, for a format string ‘field_%s’, a field named subject will get the id value ‘field_subject’.

>>> f = ContactForm(auto_id='id_for_%s')
>>> print(f.as_table())
><tr><th><label for="id_for_subject">Subject:</label></th><td><input id="id_for_subject
˓→" type="text" name="subject" maxlength="100" required></td></tr>
<tr><th><label for="id_for_message">Message:</label></th><td><input type="text" name=
˓→"message" id="id_for_message" required></td></tr>
<tr><th><label for="id_for_sender">Sender:</label></th><td><input type="email" name=
˓→"sender" id="id_for_sender" required></td></tr>
<tr><th><label for="id_for_cc_myself">Cc myself:</label></th><td><input type="checkbox
˓→" name="cc_myself" id="id_for_cc_myself"></td></tr>
>>> print(f.as_ul())
<li><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text
˓→" name="subject" maxlength="100" required></li>
<li><label for="id_for_message">Message:</label> <input type="text" name="message" id=
˓→"id_for_message" required></li>
<li><label for="id_for_sender">Sender:</label> <input type="email" name="sender" id=
˓→"id_for_sender" required></li>
<li><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_
˓→myself" id="id_for_cc_myself"></li>
>>> print(f.as_p())
<p><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text
˓→" name="subject" maxlength="100" required></p>
<p><label for="id_for_message">Message:</label> <input type="text" name="message" id=
˓→"id_for_message" required></p>
<p><label for="id_for_sender">Sender:</label> <input type="email" name="sender" id=
˓→"id_for_sender" required></p>
<p><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_
˓→myself" id="id_for_cc_myself"></p>

4)如果该属性设为其他为True的值, 例如不包含%s的字符串, 那表现将会和设为True时相同. 默认情况下设为’id_%s’;

If auto_id is set to any other true value – such as a string that doesn’t include %s – then the library will act as if auto_id is True.
By default, auto_id is set to the string ‘id_%s’.

(19)Form.label_suffix

A translatable string (defaults to a colon (: in English) that will be appended after any label name when a form is rendered.
It’s possible to customize that character, or omit it entirely, using the label_suffix parameter:

>>> f = ContactForm(auto_id='id_for_%s', label_suffix='')
>>> print(f.as_ul())
<li><label for="id_for_subject">Subject</label> <input id="id_for_subject" type="text
˓→" name="subject" maxlength="100" required></li>
<li><label for="id_for_message">Message</label> <input type="text" name="message" id=
˓→"id_for_message" required></li>
<li><label for="id_for_sender">Sender</label> <input type="email" name="sender" id=
˓→"id_for_sender" required></li>
<li><label for="id_for_cc_myself">Cc myself</label> <input type="checkbox" name="cc_
˓→myself" id="id_for_cc_myself"></li>
>>> f = ContactForm(auto_id='id_for_%s', label_suffix=' ->')
>>> print(f.as_ul())
<li><label for="id_for_subject">Subject -></label> <input id="id_for_subject" type=
˓→"text" name="subject" maxlength="100" required></li>
<li><label for="id_for_message">Message -></label> <input type="text" name="message"
˓→id="id_for_message" required></li>
<li><label for="id_for_sender">Sender -></label> <input type="email" name="sender" id=
˓→"id_for_sender" required></li>
<li><label for="id_for_cc_myself">Cc myself -></label> <input type="checkbox" name=
˓→"cc_myself" id="id_for_cc_myself"></li>

可翻译的字符串,当表单渲染时将被添加到标签名之后,可以通过此属性自己定制;如上例;

Note that the label suffix is added only if the last character of the label isn’t a punctuation character (in English, those are ., !, ? or ?.
Fields can also define their own label_suffix. This will take precedence over Form.label_suffix. The suffix can also be overridden at runtime using the label_suffix parameter to label_tag().

注意,仅当标签的最后一个字符不是标点符号时才会添加标签后缀; 字段也可以定义它们自己的标签后缀, 将会覆盖表单的标签后缀, 后缀也可以在运行时对label_tag()使用label_suffix进行覆盖;

(20)Form.use_required_attribute

When set to True (the default), required form fields will have the required HTML attribute. Formsets instantiate forms with use_required_attribute=False to avoid incorrect browser validation when adding and deleting forms from a formset.

当该属性设为True时(默认情况), 必填的字段在HTML中将会具有required属性; 当表单集在实例化对象时将会把该属性设为False以避免不正确的浏览器验证当添加或删除表单时;

(21)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.
You can also use the Form.field_order argument to a Form to override the field order. If a Form defines field_order and you include field_order when instantiating the Form, then the latter field_order will have precedence.

默认情况下,Form.field_order = None,它保留您在表单类中定义字段的顺序。 如果field_order是字段名称列表,则按列表指定的顺序排序字段,并根据默认顺序追加其余字段。 列表中的未知字段名称将被忽略。 这使得可以通过将子类设置为None来禁用子类中的字段,而无需重新定义排序。
您还可以使用Form的Form.field_order参数来覆盖字段顺序。 如果Form定义了field_order,并且在实例化Form时包含field_order,则后一个field_order将具有优先权。

Form.order_fields(field_order)
You may rearrange the fields any time using order_fields() with a list of field names as in field_order.

您可以随时使用order_fields()以及field_order中的字段名称列表重新排列字段。

(22)错误信息显示方式;

If you render a bound Form object, the act of rendering will automatically run the form’s validation if it hasn’t already happened, and the HTML output will include the validation errors as a < ul class=“errorlist”> near the field.
The particular positioning of the error messages depends on the output method you’re using:

>>> data = {'subject': '',
... 'message': 'Hi there',
... 'sender': 'invalid email address',
... 'cc_myself': True}
>>> f = ContactForm(data, auto_id=False)
>>> 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><input type="text" name="message" value="Hi there" required>
˓→</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: <input type="text" name="message" value="Hi there" required></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: <input type="text" name="message" value="Hi there" required></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>

在HTML显示时,错误信息将会在字段附近包含入< ul class=“errorlist”>标签中, 放入li标签中;示例如上;

4.BoundField绑定字段的属性及方法
(1)class BoundField

Used to display HTML or access attributes for a single field of a Form instance.
The __ str__() method of this object displays the HTML for this field.
To retrieve a single BoundField, use dictionary lookup syntax on your form using the field’s name as the key:

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

#To retrieve all BoundField objects, iterate the form:
>>> 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">

#The field-specific output honors the form object’s auto_id setting:
>>> 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>

用于显示HTML或访问单个字段的属性; 该类的__ str__()方法显示了该字段要呈现的HTML;使用见上例;

(2)BoundField.auto_id

The HTML ID attribute for this BoundField. Returns an empty string if Form.auto_id is False.

返回该字段的HTML id,如果Form.auto_id是False, 则返回空字符串;

(3)BoundField.data

This property returns the data for this BoundField extracted by the widget’s value_from_datadict() method, or None if it wasn’t given:

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

该属性返回字段的由插件的value_from_datadict() 方法提取的数据 , 如果未给出则返回None;

(4)BoundField.errors

A list-like object that is displayed as an HTML < ul class=“errorlist”> when printed:

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

一个类似列表的对象.当打印时呈现为ul标签;

(5)BoundField.field

The form Field instance from the form class that this BoundField wraps.

该绑定字段封装的表单类的表单字段实例;

(6)BoundField.form

The Form instance this BoundField is bound to.

返回该绑定字段绑定的表单实例;

(7)BoundField.help_text

The help_text of the field.

该字段的帮助信息;

(8)BoundField.html_name

The name that will be used in the widget’s HTML name attribute. It takes the form prefix into account.

插件的HTML name属性中使用的名字;

(9)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() will do this for you):

<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 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:
<label for="myFIELD">...</label><input id="myFIELD" type="text" name="my_field"required>

使用此属性渲染该字段的id;默认情况下为id_后面加字段名. 你可以在插件的attrs参数中设置字段的id,见上例;

(10)BoundField.is_hidden

Returns True if this BoundField’s widget is hidden.

判断字段的插件是否是隐藏的;

(11)BoundField.label

The label of the field. This is used in label_tag().

该字段的标签内容, 使用在label_tag()中;

(12)BoundField.name

The name of this field in the form:

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

该字段在表单中的名字,见上例;

(13)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().
This method is primarily used internally. You should use a widget instead.

返回HTML字符串,将其表示为< input type=“hidden”>, **kwargs被传入as_widget()方法,该字段主要用于内部使用,你应该使用widget;

(14)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.

通过传递的插件来渲染字段;attrs参数添加HTML属性;如果未指定插件,那么字段的默认插件将会被使用;only_initial参数被django内部使用,不应该显式调用;

(15)BoundField.css_classes()

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'

CSS类被用于指示必填字段和包含错误的字段,如果你手动渲染表单,你可用使用此方法访问CSS类;见上例; 也可用通过此方法添加css类;

(16)BoundField.label_tag(contents=None, attrs=None, label_suffix=None)

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>

You can provide the contents parameter which will replace the auto-generated label tag. An attrs dictionary may contain additional attributes for the < label> tag.
The HTML that’s generated includes the form’s label_suffix (a colon, by default) or, if set, the current field’s label_suffix. The optional label_suffix parameter allows you to override any previously set suffix. For example, you can use an empty string to hide the label on selected fields. If you need to do this in a template, you could write a custom filter to allow passing parameters to label_tag.

如果想要单独的渲染label标签, 可用使用此方法; contents参数可以替代自动生成的label标签, attrs参数可以为标签添加额外的属性;label_suffix属性允许你覆盖表单或字段中规定的label_suffix;例如你可用使用空字符串来隐藏所选字段的标签,如果你需要在模板中进行这种操作,可用写一个自定义的过滤器以向label_tag中传递参数;

(17)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

此方法将呈现字段的原始值, 因为它将被插件渲染;见上例;

5.将上传文件绑定到表单

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 – just omit both form data and file data:

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

上传文件或图片和通常的表单字段有所不同, 第一, 需要在form标签元素中绑定enctype=“multipart/form-data” 如如上所述;
第二,初始化表单绑定数据时, 需要和普通数据分开绑定, 如上例中所示;
在实际使用中, 通常使用request.POST, request.FILES绑定数据;

6.表单字段的参数
(1)Field.clean(value)

Although the primary way you’ll use Field classes is in Form classes, you can also instantiate them and use them directly to get a better idea of how they work. Each Field instance has a clean() method, which takes a single argument and either raises a django.forms.ValidationError exception or returns the clean value:

>>> 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也有clean()方法,尽管一般字段是放在表单中使用的,但也可以单独使用;该方法传入一个值然后返回clean后的数据或抛出错误;

(2)required

Field.required
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,To specify that a field is not required, pass required=False to the Field constructor;
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.

决定该字段是否是必填的;如果设为False, 当传入空值时,clean()方法会转化为空字符串或None,根据不同字段决定;

(3)label

Field.label
The label argument lets you specify the “human-friendly” label for this field. This is used when the Field is displayed in a Form.
As explained in “Outputting forms as HTML” above, the default label for a Field is generated from the field name by converting all underscores to spaces and upper-casing the first letter. Specify label if that default behavior doesn’t result in an adequate label.
Here’s a full example Form that implements label for two of its fields. We’ve specified auto_id=False to simplify the output:

>>> 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参数可以指定字段在表单中显示的名字, 默认是把字段名下划线改为空格然后首字母大写;

(4)label_suffix

Field.label_suffix
The label_suffix argument lets you override the form’s label_suffix on a per-field basis:

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

label_suffix参数可以覆盖Form的label_suffix基于每个字段;

(5)initial

Field.initial
1)The initial argument lets you specify the initial value to use when rendering this Field in an unbound Form.
To specify dynamic initial data, see the Form.initial parameter.
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>

指定字段的初始值, 可以在你想要呈现一个空表但某个字段具有初始值时使用;
注意, 如果直接在初始化表单对象时传入数据,则会触发校验, HTML中会显示错误信息;

2)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.

同时,要注意初始值不会被用作返回数据进行校验, 仅仅是用作展示,也即如果你传入一个空值, 并不会把初始值当作默认值使用, 见上例;
同时, 初始值也可以是可调用对象,可调用对象会在表单展示的时候调用而不是在表单定义的时候调用;

(6)widget

Field.widget
The widget argument lets you specify a Widget class to use when rendering this Field. See Widgets for more information.

定义使用的插件;

(7)help_text

Field.help_text
The help_text argument lets you specify descriptive text for this Field. If you provide help_text, it will be displayed next to the Field when the Field is rendered by one of the convenience Form methods (e.g., as_ul()).
Like the model field’s help_text, this value isn’t HTML-escaped in automatically generated forms.
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>

可以的定义字段的描述信息;将会显示在字段的旁边;
和模型的help_text一样, 自动生成表单时不会进行HTML转义;见上例;

(8)error_messages

Field.error_messages
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.

该参数可以覆盖默认的错误提示信息;传入一个字典,键为你想要覆盖的错误信息类型, 值为错误提示信息,见上例;

(9)validators

Field.validators
The validators argument lets you provide a list of validation functions for this field.
See the validators documentation for more information.

该参数为字段提供了一系列的验证函数;

(10)localize

Field.localize
The localize argument enables the localization of form data input, as well as the rendered output.
See the format localization documentation for more information.

localize参数使表单输入数据以及渲染的输出数据的本地化变得可用;

(11)disabled

Field.disabled
The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users. Even if a user tampers with the field’s value submitted to the server, it will be ignored in favor of the value from the form’s initial data.

当设为True时,将会使用HTML的disabled属性禁用表单字段,使用户无法编辑,即使用户篡改了提交向服务器的字段的值,也会被忽略;

(12)has_changed()

Field.has_changed()
The has_changed() method is used to determine if the field value has changed from the initial value. Returns True or False.
See the Form.has_changed() documentation for more information.

该方法用于决定该字段的值是否已经改变相对于初始值;返回True或False;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值