web框架开发-Django的Forms组件
校验字段功能
针对一个实例:用户注册。
模型:models.py
class UserInfo(models.Model): name=models.CharField(max_length=32) pwd=models.CharField(max_length=32) email=models.EmailField() tel=models.CharField(max_length=32)
模板: reg.html:
<!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>
视图函数:reg
# forms组件 from django.forms import widgets wid_01=widgets.TextInput(attrs={"class":"form-control"}) 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(): # 返回布尔值,校验的最后结果 print(form.cleaned_data) # 所有通过校验的字段以及对应的值 else: print(form.cleaned_data) # print(form.errors) # ErrorDict : {"校验错误的字段":["错误信息",]} print(form.errors.get("name")) # ErrorList ["错误信息",] return HttpResponse("OK") return render(request,"register.html",locals())
重要的点:
模板传过来的字段要和类的字段一一对应。
可以多,不能少。
如果有没有的值,即多了不存在字段,不会报错,不care没有的键值对。但是,若少了必然会是False
默认都有非空规则,如果需要的匹配的值,有找不到的,就会是False。
如果全部正确,才是True
如果有错误的,正确的放在form.cleaned_data,错误的放在forms.errors ,错误的信息作为值
forms.error.get(“xxx”)[0]取出错误信息,因为其本质的类型是一个字典
form.is_valid() :返回布尔值
form.cleaned_data :{"name":"yuan","email":"123@qq.com"}
form.errors :{"name":[".........."]}
渲染标签功能
为了更方便和快捷,以及防止输入出错,我么可以使用标签渲染
方式一
form=UserForm
{{form.字段名.lable }}
{{form.字段名 }}
需要在Form类中设置lable属性,显示别名(中文名)
view.py中
class UserForm(forms.Form): name=forms.CharField(min_length=4,label='用户名') pwd=forms.CharField(min_length=4,label='密码') pwd_r=forms.CharField(min_length=4,label='确认密码') tel=forms.CharField(label='手机号') email=forms.EmailField(label='邮箱')
reg.html
<!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>
方式二
用for循环动态添加
<form action="" method="post"> {% csrf_token %} {% for field in form %} <div> <label for="">{{ field.label }}</label> {{ field }} </div> {% endfor %} <input type="submit" class="btn btn-default pull-right"> </form>
方式三
{{form.as_p }},{{ forms.as_table }},….有很多种
固定了样式,而且不易于操作,所以不建议使用
<form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-default pull-right"> </form>
显示错误与重置输入信息功能
views.py
from django.shortcuts import render # Create your views here. from app01.models import * from django import forms from django.forms import widgets # 设置调整渲染的样式的模块 # 创建forms组件,用来校验输入 class UserForm(forms.Form): name=forms.CharField(min_length=4, # 校验长度 label='用户名', # 设置别名 error_messages={"required":'该字段不能为空'}, # 错误信息提示更改为中文 widget=widgets.TextInput(attrs={'class':'form-control'})) # 添加class类的样式 pwd=forms.CharField(min_length=4,label='密码', widget=widgets.PasswordInput(attrs={'class':'form-control'}), # 设置成password类型,并添加样式 error_messages = {"required": '该字段不能为空'} ) pwd_r=forms.CharField(min_length=4,label='确认密码', error_messages={"required":'该字段不能为空'}, widget=widgets.TextInput(attrs={'class':'form-control'}) ) tel=forms.CharField(label='手机号', error_messages={"required":'该字段不能为空','invalid':'格式错误'}, widget=widgets.TextInput(attrs={'class':'form-control'}) ) email=forms.EmailField(label='邮箱', error_messages={"required":'该字段不能为空','invalid':'格式错误'}, widget=widgets.TextInput(attrs={'class':'form-control'}) ) def reg(request): if request.method=="POST": forms=UserForm(request.POST) print('post') if forms.is_valid(): print(forms.cleaned_data) else: print(forms.is_valid()) print(forms.cleaned_data) print(forms.errors) # 重要的一步放在这里,同时保留了传过来的值,所以前端在刷新的时候,之前的输入还会存在 return render(request,'reg.html',locals()) forms=UserForm() return render(request,'reg.html',locals())
模板reg.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <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> <form action="" method="post" novalidate> {% csrf_token %} <p> {{ forms.name.label }}{{ forms.name }} <span>{{ forms.name.errors.0 }}</span> </p> <p> {{ forms.pwd.label }}{{ forms.pwd }} <span>{{ forms.pwd.errors.0 }}</span> {#.0很重要 取到第一个错误,errors得到的是一个li标签列表#} </p> <p> {{ forms.pwd_r.label }}{{ forms.pwd_r }} <span>{{ forms.pwd_r.errors.0 }}</span> {#.0很重要#} </p> <p> {{ forms.tel.label }}{{ forms.tel }} <span>{{ forms.tel.errors.0 }}</span> {#.0很重要#} </p> <p> {{ forms.email.label }}{{ forms.email }} <span>{{ forms.email.errors.0 }}</span> {#.0很重要#} </p> <input type="submit"> </form> </body> </html>
局部钩子与全局钩子
模板文件reg.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .error{ color: red; } </style> <!-- 最新版本的 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> <div class="container"> <div class="row"> <div class="col-md-6 col-lg-offset-3"> <hr> <h3>forms组件渲染方式1</h3> <form action="" method="post" novalidate> {% csrf_token %} <p>{{ form.name.label }} {{ form.name }} <span class="pull-right error">{{ form.name.errors.0 }}</span> </p> <p>{{ form.pwd.label }} {{ form.pwd }} <span class="pull-right error">{{ form.pwd.errors.0 }}</span> </p> <p>确认密码 {{ form.r_pwd }} <span class="pull-right error">{{ form.r_pwd.errors.0 }}</span>
<span class="pull-right error">{{ errors.0 }}</span> {# 全局错误 #} </p> <p>邮箱 {{ form.email }} <span class="pull-right error">{{ form.email.errors.0 }}</span></p> <p>手机号 {{ form.tel }} <span class="pull-right error">{{ form.tel.errors.0 }}</span></p> <input type="submit"> </form> </div> </div> </div> </body> </html>
视图函数views.py
from django.shortcuts import render,HttpResponse # Create your views here. from app01.myforms import * def reg(request): if request.method=="POST": print(request.POST) #form=UserForm({"name":"yu","email":"123@qq.com","xxxx":"alex"}) form=UserForm(request.POST) # form表单的name属性值应该与forms组件字段名称一致 print(form.is_valid()) # 返回布尔值 if form.is_valid(): print(form.cleaned_data) # {"name":"yuan","email":"123@qq.com"} else: print(form.cleaned_data) # {"email":123@qq.com} # 全局钩子错误 #print("error",form.errors.get("__all__")[0]) errors=form.errors.get("__all__") return render(request,"reg.html",locals()) form=UserForm() return render(request,"reg.html",locals())
将forms组件逻辑,新建文件单独放置
from django import forms from django.forms import widgets from app01.models import UserInfo from django.core.exceptions import NON_FIELD_ERRORS, ValidationError class UserForm(forms.Form): name=forms.CharField(min_length=4,label="用户名",error_messages={"required":"该字段不能为空"}, widget=widgets.TextInput(attrs={"class":"form-control"}) ) pwd=forms.CharField(min_length=4,label="密码", widget=widgets.PasswordInput(attrs={"class":"form-control"}) ) r_pwd=forms.CharField(min_length=4,label="确认密码",error_messages={"required":"该字段不能为空"},widget=widgets.TextInput(attrs={"class":"form-control"})) email=forms.EmailField(label="邮箱",error_messages={"required":"该字段不能为空","invalid":"格式错误"},widget=widgets.TextInput(attrs={"class":"form-control"})) tel=forms.CharField(label="手机号",widget=widgets.TextInput(attrs={"class":"form-control"})) 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("手机号格式错误") def clean(self): # 全局钩子 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