Forms组件
一、Form组件介绍
Form组件可以做的几件事情:
1、用户请求数据验证
2、自动生成错误信息
3、打包用户提交的正确信息
4、如果其中有一个错误了,其他的正确这,保留上次输入的内容
4、自动创建input标签并可以设置样式
二、Form组件的使用
1、创建规则
from django import forms from django.forms import widgets from app01.models import * from django.forms import ValidationError #下面的import和这里效果一样 # from django.core.exceptions import ValidationErrorclass 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=8,label='密码',error_messages={'required':'该字段不能为空!'}, widget=widgets.PasswordInput(attrs={'class':'form-control'})) r_pwd =forms.CharField(min_length=8,label='确认密码',error_messages={'required':'该字段不能为空!'}, widget=widgets.PasswordInput(attrs={'class':'form-control'})) tel = forms.CharField(label='手机号码',error_messages={'required':'该字段不能为空!'}, widget=widgets.TextInput(attrs={'class':'form-control'})) email =forms.EmailField(label='邮箱',error_messages={'required':'该字段不能为空!'}, widget=widgets.TextInput(attrs={'class':'form-control'}))
2.规则匹配
error_messages={'错误字段':'提示信息'}
widget=widgets.TextInput(attrs={'class':'form-control'}):给text类型的input框添加一个class属性,值为form-control
widgets.PasswordInput:表示密码输入框.
def clean_字段名:局部校验钩子,针对某一个字段编写校验规则.
def clean(self):全局校验钩子,可以取出所有的字段值,进行校验.用于校验2个字段的值是否相同(校验密码与确认秘密).
self.cleaned_data:是在全局校验中,所有的干净数据(已经通过校验的数据).
myforms.py文件:
# *_*coding:utf-8 *_* from django import forms from django.forms import widgets from app01.models import * from django.forms import ValidationError #下面的import和这里效果一样 # from django.core.exceptions import ValidationError class UserForm(forms.Form): # 这个类里的属性名必须和前端中form表单中name属性值一致 # 校验时,如果有任意一个不符合规则,就false ''' error_messages={'错误类型':'错误提示'} widgets.TextInput(attrs={'属性名':'属性值'}) ''' name = forms.CharField(min_length=4,label='用户名',error_messages={'required':'该字段不能为空!'}, widget=widgets.TextInput(attrs={'class':'form-control'})) pwd =forms.CharField(min_length=8,label='密码',error_messages={'required':'该字段不能为空!'}, widget=widgets.PasswordInput(attrs={'class':'form-control'})) r_pwd =forms.CharField(min_length=8,label='确认密码',error_messages={'required':'该字段不能为空!'}, widget=widgets.PasswordInput(attrs={'class':'form-control'})) tel = forms.CharField(label='手机号码',error_messages={'required':'该字段不能为空!'}, widget=widgets.TextInput(attrs={'class':'form-control'})) email =forms.EmailField(label='邮箱',error_messages={'required':'该字段不能为空!'}, widget=widgets.TextInput(attrs={'class':'form-control'})) # 局部钩子 def clean_name(self): val = self.cleaned_data.get('name') is_true = userinfo.objects.filter(name=val) if is_true: raise ValidationError('该用户已经存在!') else: return val def clean_tel(self): val =self.cleaned_data.get('tel') if len(val)==11 and val.startswith('1'): return val else: raise ValidationError("手机号码格式不对,必须是1开头") # 全局钩子 def clean(self): pwd =self.cleaned_data.get('pwd') r_pwd =self.cleaned_data.get('r_pwd') # 校验密码时,如果pwd或者r_pwd,校验规则时不通过的话,那么就不应该让它俩进行比对.校验不通过值是none if pwd and r_pwd: if pwd==r_pwd: return self.cleaned_data else: raise ValidationError('两次密码不一致') else: return self.cleaned_data
views.py:校验逻辑代码
form =UserForm(request.POST):所有的请求数据都在POST中,先实例化一个对象
is.valid():这个是用来进行校验的
from django.shortcuts import render,HttpResponse from app01.myforms import * # Create your views here. def reg(request): if request.method=="POST": print(request.POST) form = UserForm(request.POST) # form.is_valid() 是校验结果,如果校验通过返回true,否则返回false print(form.is_valid()) if form.is_valid(): # form.cleaned_data:通过后的数据,是一个字典形式.{'key':value} print(form.cleaned_data) return HttpResponse('验证通过') else: # form.cleaned_data:出现在校验失败的逻辑中,则表示校验成功的字段信息. print(form.cleaned_data) # form.erros:返回的校验不通过的信息,格式为:{'不通过的字段':[不通过原因]} # 取全局错误 errors = form.errors.get('__all__') print(errors) print(form.errors) for i in form.errors: print(form.errors.get(i)[0])#获取错误信息 '''校验失败返回页面: 此次返回的页面和get请求不一样,get请求中form中是没有数据的.这次返回的form中有数据,那么会自动渲染数据 这样的好处就是,填写的数据不会被清空,而是被渲染到标签中 ''' return render(request, 'reg.html', locals()) form = UserForm() return render(request,'reg.html',locals())
reg.html
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>forms表单校验</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body> <div class="cent" style="width: 30%;margin: 0 auto"> <h3>forms组件渲染form表单2</h3> <form action="" method="post"> {% csrf_token %} {% for foo in form %} <div style="margin: 5px "><label for="">{{ foo.label }}</label> {{ foo }} <span style="color:red" class="pull-right">{{ foo.errors.0 }}</span> {% if errors.0 and foo.name == 'r_pwd' %} 用来判断全局错误中,是否是确认密码的错误提示. <span style="color:red" class="pull-right">{{ errors.0 }}</span> {% endif %} </div> {% endfor %} <input type="submit"> </form> </div> </body> </html>
来源:https://www.cnblogs.com/lovepy3/p/10959845.html