forms组件
一,校验字段功能
-forms是什么?
就是一个类,可以校验字段(前台传过来的字段)
-怎么用:
针对一个实例:注册用户讲解。
模型:models.py
class UserInfo(models.Model): # 写一个类,要校验那些字段,就是类的属性
name=models.CharField(max_length=32) # 定义一个属性,可以用来校验字符串类型
pwd=models.CharField(max_length=32)
email=models.EmailField()
模板文件里:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
<div>
<label for="user">用户名</label>
<p><input type="text" name="name" id="name"></p>
</div>
<div>
<label for="pwd">密码</label>
<p><input type="password" name="pwd" id="pwd"></p>
</div>
<div>
<label for="r_pwd">确认密码</label>
<p><input type="password" name="r_pwd" id="r_pwd"></p>
</div>
<div>
<label for="email">邮箱</label>
<p><input type="text" name="email" id="email"></p>
</div>
<input type="submit">
</form>
</body>
</html>
视图函数里:
# forms组件
from django.forms import widgets
wid_01=widgets.TextInput(attrs={"class":"form-control"}) #控制input输入框的格式,括号里面是控制的样式
wid_02=widgets.PasswordInput(attrs={"class":"form-control"}) #控制密码框,这样密码就是密文格式
class UserForm(forms.Form): #重写一个类
name=forms.CharField(max_length=32,
widget=wid_01
)
pwd=forms.CharField(max_length=32,widget=wid_02)
r_pwd=forms.CharField(max_length=32,widget=wid_02)
email=forms.EmailField(widget=wid_01)
tel=forms.CharField(max_length=32,widget=wid_01)
def register(request):
if request.method=="POST":
form=UserForm(request.POST) #实例化出来一个对象,#实例化产生对象,传入要校验的数据(字典)
if form.is_valid(): #判断is_valid如果是true,校验成功
print(form.cleaned_data) # 所有干净的字段以及对应的值
else:
print(form.cleaned_data) #
print(form.errors) # ErrorDict : {"校验错误的字段":["错误信息",]}
print(form.errors.get("name")) # ErrorList ["错误信息",]
return HttpResponse("OK")
form=UserForm()
return render(request,"register.html",locals())
-注意:校验的字段,可以多,但是不能少
二 渲染标签功能
渲染方式一:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<h3>注册页面</h3>
<div class="container">
<div class="row">
<div class="col-md-6 col-lg-offset-3">
<form action="" method="post">
{% csrf_token %}
<div>
<label for="">用户名</label>
{{ form.name }}
</div>
<div>
<label for="">密码</label>
{{ form.pwd }}
</div>
<div>
<label for="">确认密码</label>
{{ form.r_pwd }}
</div>
<div>
<label for=""> 邮箱</label>
{{ form.email }}
</div>
<input type="submit" class="btn btn-default pull-right">
</form>
</div>
</div>
</div>
</body>
</html>
渲染方式2
<h1>第二种方式(for循环form对象,建议用这种)</h1>
<form action="" method="post" >
{% for foo in myform %}
<p>{{ foo.label }}:{{ foo }}</p>
{% endfor %}
<input type="submit" value="提交">
</form>
渲染方式3
<h1>第三种方式(不建议用)</h1>
<form action="" method="post" >
{# {{ myform.as_p }}#}
{{ myform.as_ul }}
<input type="submit" value="提交">
</form>
</body>
</html>
三渲染错误信息功能
- myforms有errors
-属性(name)也有errors
-错误信息,变成中文:
视图里:
def register(request):
if request.method=="POST":
form=UserForm(request.POST)
if form.is_valid():
print(form.cleaned_data) # 所有干净的字段以及对应的值
else:
print(form.cleaned_data) #
print(form.errors) # ErrorDict : {"校验错误的字段":["错误信息",]}
print(form.errors.get("name")) # ErrorList ["错误信息",]
return render(request,"register.html",locals())
form=UserForm()
return render(request,"register.html",locals())
模板里:
<form action="" method="post" novalidate>
{% for foo in myform %} #循环出来的是要校验的字段
<p>{{ foo.label }}:{{ foo }} <span>{{ foo.errors.0 }}</span></p>
{% endfor %}
<input type="submit" value="提交"><span>{{ all_error }}</span>
</form>
四 局部钩子:
-定义一个函数,名字叫:clean_字段名字,内部,取出该字段,进行校验,如果通过,将该字段返回,如果失败,抛异常(ValidationError)
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
def clean_name(self):
val=self.cleaned_data.get("name")
ret=UserInfo.objects.filter(name=val)
if not ret:
return val
else:
raise ValidationError("该用户已注册!")
def clean_tel(self):
val=self.cleaned_data.get("tel")
if len(val)==11:
return val
else:
raise ValidationError("手机号格式错误")
五 全局钩子:
#重写clean方法
def clean(self):
#程序能走到该函数,前面校验已经通过了,所以可以从cleaned_data中取出密码和确认密码
pwd=self.cleaned_data.get('pwd')
r_pwd=self.cleaned_data.get('r_pwd')
if pwd and r_pwd:
if pwd==r_pwd:
return self.cleaned_data
else:
raise ValidationError('两次密码不一致')
else:
return self.cleaned_data