一.form介绍
需要对用户的输入做校验,比如校验用户是否输入,输入的长度和格式等正不正确。如果用户输入的内容有错误就需要在页面上相应的位置显示对应的错误信息.。
Django form组件就实现了上面所述的功能。
总结一下,其实form组件的主要功能如下:
- 生成页面可用的HTML标签
- 对用户提交的数据进行校验
- 保留上次输入内容
二.Form常用字段与插件
创建Form类时,主要涉及到 【字段】 和 【插件】,字段用于对用户请求数据的验证,插件用于自动生成HTML
TextInput
默认是TextInput,如果想加样式可以在括号里面写。
name = forms.CharField(
label='用户名', #标签
min_length=6, #最小长度
max_length=12, #最大长度
widget=forms.widgets.TextInput(attrs={'class':'form-control'}) #增加样式
)
PasswordInput
password = forms.CharField(
min_length=6,
max_length=8,
widget=forms.widgets.PasswordInput(attrs={'class':'form-control'}) #加密输入
)
日期
date_local = forms.CharField(
widget=forms.widgets.TextInput(attrs={'type':'date'})
)
错误信息和帮助文本
password = forms.CharField(
min_length=6,
max_length=8,
error_messages={'min_length':'最小6位','max_length':'最大8位'}, #提示错误信息
help_text='输入密码!', #帮助文本
widget=forms.widgets.PasswordInput(attrs={'class':'form-control'}) #加密输入
)
RadioSelect
# 单选input框
sex = forms.ChoiceField(
label='性别',
choices=[('1','女'),('2','男'),('3','保密')], #选项列表
initial=3, #默认选中
widget=forms.widgets.RadioSelect(),
)
Select
# 单选下拉框
hobby = forms.ChoiceField(
label='爱好',
choices=[('1','羽毛球'),('2','篮球'),('3','网球')],
widget=forms.widgets.Select()
)
SelectMultiple
# 多选下拉框
city = forms.MultipleChoiceField(
label='城市',
choices=[('1','北京'),('2','上海'),('3','南京'),('4','广州')],
widget=forms.widgets.SelectMultiple(),
)
CheckboxSelectMultiple
# 多选checkbox
label_tag = forms.MultipleChoiceField(
label='标签',
choices=[('1', 'IE'), ('2', 'firefox'), ('3', 'chrome'), ('4', 'opera')],
widget=forms.widgets.CheckboxSelectMultiple(),
)
CheckboxInput
# 单选checkbox
status = forms.ChoiceField(
choices=[('1','True'),('2','False')],
widget=forms.widgets.CheckboxInput(),
)
html文件:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
</head>
<body>
<h1>form</h1>
<form action="" method="post" novalidate>
{% csrf_token %}
<div>
<label for="">{{ forms_obj.name.label }}</label>
{{ forms_obj.name }}
</div>
<div>
<label for="">{{ forms_obj.password.label }}</label>
{{ forms_obj.password }}
</div>
<div>
<label for="">{{ forms_obj.date_local.label }}</label>
{{ forms_obj.date_local }}
</div>
<div>
<label for="">{{ forms_obj.status.label }}</label>
{{ forms_obj.status }}
</div>
<div>
<label for="">{{ forms_obj.sex.label }}</label>
{{ forms_obj.sex }}
</div>
<div>
<label for="">{{ forms_obj.city.label }}</label>
{{ forms_obj.city }}
</div>
<div>
<label for="">{{ forms_obj.hobby.label }}</label>
{{ forms_obj.hobby }}
</div>
<div>
<label for="">{{ forms_obj.label_tag.label }}</label>
{{ forms_obj.label_tag }}
</div>
<input type="submit">
</form>
</body>
</html>
页面展示:
三.Form所有内置字段
Field
required=True, 是否允许为空
widget=None, HTML插件
label=None, 用于生成Label标签或显示内容
initial=None, 初始值
help_text='', 帮助信息(在标签旁边显示)
error_messages=None, 错误信息 {'required': '不能为空', 'invalid': '格式错误'}
validators=[], 自定义验证规则
localize=False, 是否支持本地化
disabled=False, 是否可以编辑
label_suffix=None Label内容后缀
CharField(Field)
max_length=None, 最大长度
min_length=None, 最小长度
strip=True 是否移除用户输入空白
IntegerField(Field)
max_value=None, 最大值
min_value=None, 最小值
FloatField(IntegerField)
...
DecimalField(IntegerField)
max_value=None, 最大值
min_value=None, 最小值
max_digits=None, 总长度
decimal_places=None, 小数位长度
BaseTemporalField(Field)
input_formats=None 时间格式化
DateField(BaseTemporalField) 格式:2015-09-01
TimeField(BaseTemporalField) 格式:11:12
DateTimeField(BaseTemporalField)格式:2015-09-01 11:12
DurationField(Field) 时间间隔:%d %H:%M:%S.%f
...
RegexField(CharField)
regex, 自定制正则表达式
max_length=None, 最大长度
min_length=None, 最小长度
error_message=None, 忽略,错误信息使用 error_messages={'invalid': '...'}
EmailField(CharField)
...
FileField(Field)
allow_empty_file=False 是否允许空文件
ImageField(FileField)
...
注:需要PIL模块,pip3 install Pillow
以上两个字典使用时,需要注意两点:
- form表单中 enctype="multipart/form-data"
- view函数中 obj = MyForm(request.POST, request.FILES)
URLField(Field)
...
BooleanField(Field)
...
NullBooleanField(BooleanField)
...
ChoiceField(Field)
...
choices=(), 选项,如:choices = ((0,'上海'),(1,'北京'),)
required=True, 是否必填
widget=None, 插件,默认select插件
label=None, Label内容
initial=None, 初始值
help_text='', 帮助提示
ModelChoiceField(ChoiceField)
... django.forms.models.ModelChoiceField
queryset, # 查询数据库中的数据
empty_label="---------", # 默认空显示内容
to_field_name=None, # HTML中value的值对应的字段
limit_choices_to=None # ModelForm中对queryset二次筛选
ModelMultipleChoiceField(ModelChoiceField)
... django.forms.models.ModelMultipleChoiceField
TypedChoiceField(ChoiceField)
coerce = lambda val: val 对选中的值进行一次转换
empty_value= '' 空值的默认值
MultipleChoiceField(ChoiceField)
...
TypedMultipleChoiceField(MultipleChoiceField)
coerce = lambda val: val 对选中的每一个值进行一次转换
empty_value= '' 空值的默认值
ComboField(Field)
fields=() 使用多个验证,如下:即验证最大长度20,又验证邮箱格式
fields.ComboField(fields=[fields.CharField(max_length=20), fields.EmailField(),])
MultiValueField(Field)
PS: 抽象类,子类中可以实现聚合多个字典去匹配一个值,要配合MultiWidget使用
SplitDateTimeField(MultiValueField)
input_date_formats=None, 格式列表:['%Y--%m--%d', '%m%d/%Y', '%m/%d/%y']
input_time_formats=None 格式列表:['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']
FilePathField(ChoiceField) 文件选项,目录下文件显示在页面中
path, 文件夹路径
match=None, 正则匹配
recursive=False, 递归下面的文件夹
allow_files=True, 允许文件
allow_folders=False, 允许文件夹
required=True,
widget=None,
label=None,
initial=None,
help_text=''
GenericIPAddressField
protocol='both', both,ipv4,ipv6支持的IP格式
unpack_ipv4=False 解析ipv4地址,如果是::ffff:192.0.2.1时候,可解析为192.0.2.1, PS:protocol必须为both才能启用
SlugField(CharField) 数字,字母,下划线,减号(连字符)
...
UUIDField(CharField) uuid类型
四.字段校验
def test1_register(request):
forms_obj = Register_Model()
if request.method == 'GET':
return render(request,'formtest/test_register1.html',{'forms_obj':forms_obj})
else:
forms_obj = Register_Model(request.POST)
if forms_obj.is_valid():
print(forms_obj.cleaned_data)
return HttpResponse('ok')
else:
print(forms_obj.errors)
return render(request, 'formtest/test_register1.html', {'forms_obj': forms_obj})
解释:
1.is_valid:数据全部正确会返回一个True 反之False
2.cleaned_data:所有校验正确的数据都在这个里面
3.errors:所有的错误信息 是一个li标签,他认为你字段会有多个错误(长度、不能为空等)
4.forms_obj = Register_Model(request.POST):将用户传进来的数据交给我们的form类进行校验
5.为什么校验错误之后又重新把页面返回给前端,第二次forms_obj是带有错误信息的页面,返回给前端进行展示
6.forms_obj = Register_Model() 将forms_obj传给前端是为了给我们生成标签用的
前端:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
</head>
<body>
<h1>form</h1>
<form action="" method="post" novalidate>
{% csrf_token %}
<div>
<label for="">{{ forms_obj.name.label }}</label>
{{ forms_obj.name }}
<span style="color: red;font-size: 14px">{{ forms_obj.name.errors.0 }}</span>
</div>
<div>
<label for="">{{ forms_obj.password.label }}</label>
{{ forms_obj.password }}
<span style="color: red;font-size: 14px">{{ forms_obj.password.errors.0 }}</span>
</div>
<input type="submit">
</form>
</body>
</html>
解释:
1. forms_obj.name.label:name是CharField实例化的对象,对象调用里面的label标签
2. forms_obj.name:字段名称
3. forms_obj.name.errors.0:name有可能是多个错误,比方说为空,长度大了或小了,这里是0 就是取第一个错误,如果只写errors就会把所有的错误信息展示出来
name = forms.CharField(
required=True, #默认就是True
validators=[RegexValidator(r'^123','必须123开头!!'),RegexValidator(r'456$','必须456结尾!!')], #校验器
error_messages={'min_length': '最小6位', 'max_length': '最大8位','required':'不能为空'}, # 提示错误信息
widget=forms.widgets.TextInput(attrs={'class':'form-control'})
)
效果:
自定义校验器:
# 自定义校验器
def mobile_validate_phone(value):
mobile_re = re.compile(r'^139[0-9]{8}')
if not mobile_re.match(value):
raise ValidationError('手机号码格式不正确')
class Register_Model(forms.Form):
name = forms.CharField(
label='用户名', #标签
validators=[mobile_validate_phone], #直接写函数名
widget=forms.widgets.TextInput(attrs={'class':'form-control'})
)
结果:
五.Hook钩子方法
除了上面定义的校验方法和校验函数外,我们还可以在Form类中定义钩子函数,来实现自定义的验证功能。
局部钩子:
def clean_name(self):
value = self.cleaned_data['name']
if '123' in value:
raise ValidationError('含有敏感词:123!!')
else:
return value
解释:
1.clean_字段名称
2.如果没有错误需要把数据返回,放回cleaned_data里面
3.ValidationError 异常
全局钩子:
判断两次密码输入是否一致。
def clean(self):
value = self.cleaned_data
p1 = value['password']
p2 = value['r_password']
if p1 == p2:
return value
else:
self.add_error('r_password','两次输入密码不一致!!!')
raise ValidationError('两次输入密码不一致!!!')
解释:
1.self.add_error:需要给那个字段添加错误信息
2.raise ValidationError('两次输入密码不一致!!!'):需要把错误信息给抛出来
3.全局钩子定义:def clean() 后面不跟字段名
結果:
六 .校验流程源码分析
data就是我们传进去的数据forms_obj = Register_Model(request.POST),所以self.is_bound肯定是为真的,下面就看self.errors里面的规则:
先看self._clean_fields():
最后执行self._clean_form()方法:
执行流程:
请求过来进入is_valid进行校验,self.is_bound和self.errors同事成立会返回True,则数据校验成功,第一步首先看self.is_bound中有没有数据,如果没有数据则返回False,则数据校验失败返回给用户,如果self.is_bound中有数据,下一步进入self.errors中进行判断,看self._errors是不是为None,这个肯定为None上面__init__初始化中已经定义为None了,所以条件肯定成立,成立就走self.full_clean(),里面会有两个字典,一个是错误信息的字典,一个是数据校验成功后的字典,首先执行self._clean_fields(),循环我们自定义类中的所有字段和校验规则,下面用反射是获取我们类中有没有定义局部钩子如果有就执行我们的局部钩子,并把数据放到cleaned_data中,如果有异常就将异常添加到error_dict中,最后执行我们的全局钩子。