1、校验字段功能
针对 一个实例:注册 用户讲解。
模型:models .py
class User(models.Model): name = models.CharField(max_length=32) pwd = models.CharField(max_length=32) email = models.EmailField(null=True)
视图函数
from django.shortcuts import render, redirect, HttpResponse from django import forms from django.forms import widgets from django.core.exceptions import ValidationError # form组件数据校验字段的功能 # 第一步:继承Form # 先写一个类 class MyForm(forms.Form): # 定义一个属性,可以用来校验字符串的属性 # 限制最大长度8,最小长度3 :max_length=8, min_length=3
# widget = widgets.PasswordInput指定input框 格式 name = forms.CharField(max_length=8, min_length=3, label='用户名', error_messages={'max_length': '最长8', 'min_length': '最小长度3', 'required': '这个 必填'}, widget=widgets.TextInput(attrs={'class': 'form-control'})) # required = True,默认为True pwd = forms.CharField(max_length=8, min_length=3, required=True, label='密码', error_messages= {'max_length': '最长8', 'min_length': '最小长度3', 'required': '这个 必填'}, widget=widgets.PasswordInput()) re_pwd = forms.CharField(max_length=8, min_length=3, required=True, label='密码', error_messages= {'max_length': '最长8', 'min_length': '最小长度3', 'required': '这个 必填'}, widget=widgets.PasswordInput()) # 校验是否为邮箱格式 # 校验是否为邮箱格式 email = forms.EmailField(label='邮箱', error_messages={'required': '这个 必填', 'invalid': '不符合 邮箱格式'})
def index_from(request): # 生成对象是,需要传入要校验的数据(字典) dic = {'name': 'xcc', 'pwd': '12', 'email': '33@qq.com'} myform = MyForm(dic) # is_valid如果是true表示校验成功,反之,校验失败 if myform.is_valid(): # 校验通过的数据 print(myform.cleaned_data) return HttpResponse('校验成功') else: print(myform.cleaned_data) # 错误的信息,它是一个字典 print(myform.errors) # 打印出错误信息 print(myform.errors.as_data()) print(type(myform.errors)) return HttpResponse('校验失败')
模板函数
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> <p>用户名:<input type="text" name="name"></p> <p>密码:<input type="text" name="pwd"></p> <p>确认密码::<input type="text" name="pwd"></p> <p>邮箱:<input type="text" name="email"></p> <input type="submit" value="提交"> </form> </body> </html>
2、渲染标签功能
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>第一种方式</h1> <form action="" method="post"> <p>用户名:{{ myform.name }}</p> <p>密码:{{ myform.pwd }}</p> <p>邮箱:{{ myform.email }}</p> <input type="submit" value="提交"> </form> <hr> <h1>第二种方式(for循环form对象)</h1> <h1>他打印的是英文,需要换成中文</h1> <form action="" method="post"> {% for foo in myform %} <p>{{ foo.label }}:{{ foo }}</p> {% endfor %} <input type="submit" value="提交"> </form> <hr> <h1>第三种方法(不建议用)</h1> <form action="" method="post"> {# {{ myform.as_ul }}#} {{ myform.as_p }} <input type="submit" value="提交"> </form> </body> </html>
3、渲染错误信息功能
视图层
from django.shortcuts import render, redirect, HttpResponse from django import forms from django.forms import widgets from django.core.exceptions import ValidationError class MyForm(forms.Form): # 定义一个属性,可以用来校验字符串的属性 # 限制最大长度8,最小长度3 # widget = widgets.PasswordInput指定input框 格式 name = forms.CharField(max_length=8, min_length=3, label='用户名', error_messages={'max_length': '最长8', 'min_length': '最小长度3', 'required': '这个 必填'}, widget=widgets.TextInput(attrs={'class': 'form-control'})) # required = True,默认为True pwd = forms.CharField(max_length=8, min_length=3, required=True, label='密码', error_messages= {'max_length': '最长8', 'min_length': '最小长度3', 'required': '这个 必填'}, widget=widgets.PasswordInput()) re_pwd = forms.CharField(max_length=8, min_length=3, required=True, label='密码', error_messages= {'max_length': '最长8', 'min_length': '最小长度3', 'required': '这个 必填'}, widget=widgets.PasswordInput()) # 校验是否为邮箱格式 # 校验是否为邮箱格式 email = forms.EmailField(label='邮箱', error_messages={'required': '这个 必填', 'invalid': '不符合 邮箱格式'}) from app01 import models def index_from(request): # 生成对象是,需要传入要校验的数据(字典) if request.method == 'GET': myform = MyForm() elif request.method == 'POST': myform = MyForm(request.POST) if myform.is_valid(): # 成功索引数据 print(myform.cleaned_data) # models.User.objects.create(name='xcc',pwd='123') myform.cleaned_data.pop('re_pwd') models.User.objects.create(**myform.cleaned_data) return redirect('http://www.baidu.com') else: all_error=myform.errors.get('__all__') if all_error: all_error=all_error[0] print(myform.errors.as_data) return render(request, 'index3.html', locals())
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <hr> <h1>第二种方式(for循环form对象)</h1> <h1>渲染错误信息</h1> {#novalidate:是错误信息不校验#} <form action="" method="post" novalidate> {% for foo in myform %} {# foo.error.0:第0个错误 了 #} <p>{{ foo.label }}:{{ foo }} <span>{{ foo.errors.0 }}</span></p> {% endfor %} <input type="submit" value="提交">{{ all_error}} </form> </body> </html>
4、组件的参数配置
class MyForm(forms.Form): # 定义一个属性,可以用来校验字符串的属性 # 限制最大长度8,最小长度3 # widget = widgets.PasswordInput指定input框 格式 name = forms.CharField(max_length=8, min_length=3, label='用户名', error_messages={'max_length': '最长8', 'min_length': '最小长度3', 'required': '这个 必填'}, widget=widgets.TextInput(attrs={'class': 'form-control'})) # required = True,默认为True pwd = forms.CharField(max_length=8, min_length=3, required=True, label='密码', error_messages= {'max_length': '最长8', 'min_length': '最小长度3', 'required': '这个 必填'}, widget=widgets.PasswordInput()) re_pwd = forms.CharField(max_length=8, min_length=3, required=True, label='密码', error_messages= {'max_length': '最长8', 'min_length': '最小长度3', 'required': '这个 必填'}, widget=widgets.PasswordInput()) # 校验是否为邮箱格式 # 校验是否为邮箱格式 email = forms.EmailField(label='邮箱', error_messages={'required': '这个 必填', 'invalid': '不符合 邮箱格式'})
5、局部钩子
’
# 局部钩子校验 def clean_name(self): # self:当前form对象 name = self.cleaned_data.get('name') if name.startswith('sb'): # 失败,抛异常 raise ValidationError('不能以傻逼开头') # 正常,把name返回 return name
6、全局钩子
def clean(self): pwd = self.cleaned_data.get('pwd') re_pwd = self.cleaned_data.get('re_pwd') if pwd == re_pwd: return self.cleaned_data else: raise ValidationError('两次密码不一致')
例子:
pwd_err=my_form.errors.get('__all__')
class MyForm(forms.Form): # 定义一个属性,可以用来校验字符串的属性 # 限制最大长度8,最小长度3 # widget = widgets.PasswordInput指定input框 格式 name = forms.CharField(max_length=8, min_length=3, label='用户名', error_messages={'max_length': '最长8', 'min_length': '最小长度3', 'required': '这个 必填'}, widget=widgets.TextInput(attrs={'class': 'form-control'})) # required = True,默认为True pwd = forms.CharField(max_length=8, min_length=3, required=True, label='密码', error_messages= {'max_length': '最长8', 'min_length': '最小长度3', 'required': '这个 必填'}, widget=widgets.PasswordInput()) re_pwd = forms.CharField(max_length=8, min_length=3, required=True, label='密码', error_messages= {'max_length': '最长8', 'min_length': '最小长度3', 'required': '这个 必填'}, widget=widgets.PasswordInput()) # 校验是否为邮箱格式 # 校验是否为邮箱格式 email = forms.EmailField(label='邮箱', error_messages={'required': '这个 必填', 'invalid': '不符合 邮箱格式'}) # choice = forms.CharField(label='选择',error_messages={'required':'这个 必填','invalid':'不符合 邮箱格式'}, # widget=widgets.CheckboxInput()) # 局部钩子校验 def clean_name(self): # self:当前form对象 name = self.cleaned_data.get('name') if name.startswith('sb'): # 失败,抛异常 raise ValidationError('不能以傻逼开头') # 正常,把name返回 return name def index_from(request): # 生成对象是,需要传入要校验的数据(字典) if request.method == 'GET': myform = MyForm() elif request.method == 'POST': myform = MyForm(request.POST) if myform.is_valid(): # 成功索引数据 print(myform.cleaned_data) # models.User.objects.create(name='xcc',pwd='123') myform.cleaned_data.pop('re_pwd') models.User.objects.create(**myform.cleaned_data) return redirect('http://www.baidu.com') else: all_error=myform.errors.get('__all__') if all_error: all_error=all_error[0] print(myform.errors.as_data) return render(request, 'index3.html', locals())
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <hr> <h1>第二种方式(for循环form对象)</h1> <h1>渲染错误信息</h1> {#novalidate:是错误信息不校验#} <form action="" method="post" novalidate> {% for foo in myform %} {# foo.error.0:第0个错误 了 #} <p>{{ foo.label }}:{{ foo }} <span>{{ foo.errors.0 }}</span></p> {% endfor %} <input type="submit" value="提交">{{ all_error}} </form> </body> </html>