利用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 – 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 data 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 .
• 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 .
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 .
• 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 .
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 .
• 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 that wraps the file content and file name into a single .
• 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 , 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 that wraps the file content and file name into a single .
• 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 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 Validati ).

默认插件:NullBooleanSelect;
空值: None;
规范化为:True, False, value;
有效性:判断给出列表中的每个值是否在choices列表中并且是否可转化;
错误信息的键:从来不报错;

(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 .
• Error message keys: required, invalid
Takes one required argument:
regex
A regular specified either as a string or a compiled regular .
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 .
• 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 .
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 .
• 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):
...
Validati : [\'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 (in the case of ModelChoiceField) or multiple model s (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 , 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 s 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 .
By default it is set to None, in which case the primary key of each 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\"> 1</option>
<option value=\"obj2.pk\"> 2</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\"> 1</option>
<option value=\"obj2.name\"> 2</option>
...
</select>

The __ str__() method of the model will be called to generate string representations of the s for use in the field’s choices. To provide customized representations, subclass ModelChoiceField and override label_from_instance. This method will receive a model 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   #%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 s, suitable for representing a many-to-many relation. As with ModelChoiceField, you can use label_from_instance to customize the 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 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 ing attack. It’s trivial to do so using a 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 Validati . See Raising Validati 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参数可以是字符串或者Validati 的实例;
注意此方法自动从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 Validati s that are raised in Form.clean() and errors added using Form.add_error(None, “…”).

返回非字段错误信息的列表,包括Form.clean()方法抛出的Validati s和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:



					
				
收藏 打印
您的足迹: