03、 forms组件
1、校验字段功能
1、reg页面准备
models
from django.db import models class UserInfo(models.Model): useranme = models.CharField(max_length=32) password = models.CharField(max_length=32) email = models.EmailField() telephone = models.CharField(max_length=32)
生成数据表
C:\PycharmProjects\formsdemo>python manage.py makemigrations
C:\PycharmProjects\formsdemo>python manage.py migrate
主url
from django.contrib import admin
from django.urls import path, re_path, include
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^', include(('app01.urls', 'app01')))
]
url
from django.urls import path, re_path, include
from app01 import views
urlpatterns = [
re_path(r'reg/$', views.reg, name='reg'),
]
模板层
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> {% csrf_token %} <p>用户名 <input type="text" name="user"></p> <p>密码 <input type="password" name="pwd"></p> <p>确认密码 <input type="password" name="_pwd"></p> <p>邮箱 <input type="text" name="email"></p> <p>手机号 <input type="text" name="tel"></p> <input type="submit" value="注册"> </form> </body> </html>
view
from django.shortcuts import render, HttpResponse def reg(request): if request.method == 'POST': print(request.POST) return HttpResponse('注册成功') return render(request, 'reg.html')
<QueryDict: {'csrfmiddlewaretoken': ['5EwZsUEKRVj836bplmS03PVruttZhG'], 'user': ['alex'], 'pwd': ['123'], '_pwd': ['123'], 'email': ['123@qq.com'], 'tel': ['1234566778']}>
2、定义规则
from django import forms # 导入forms组件 # 定义校验规则 class UserForm(forms.Form): name = forms.CharField(min_length=4, max_length=10) email = forms.EmailField()
3、form.is_valid()
reg视图代码
from django.shortcuts import render, HttpResponse # Create your views here. from django import forms # 导入forms组件 # 定义校验规则 class UserForm(forms.Form): name = forms.CharField(min_length=4, max_length=10) email = forms.EmailField() def reg(request): if request.method == 'POST': # 1.form.is_valid() 是否通过验证 form = UserForm({'name': 'alex', 'email': '123@qq.com'}) print(form.is_valid()) # True 返回布尔值 form = UserForm({'name': 'a', 'email': '123'}) print(form.is_valid()) # False form = UserForm({'name': 'alex', 'email': '123@qq.com', 'age': '33'}) print(form.is_valid()) # True # form = UserForm({'name': 'alex', 'xxx': '123@qq.com'}) print(form.is_valid()) # False form = UserForm({'name': 'a', 'email': '123', 'xxx': '123'}) print(form.is_valid()) # False if form.is_valid(): pass else: pass """ forms组件只会校验定义过的字段, 定义的data,必须满足条件且存在 True 多余的字段,不影响 """ return HttpResponse('注册成功') return render(request, 'reg.html')
4、form.cleaned_data:清洗过的数据 form.errors:报错信息
from django.shortcuts import render, HttpResponse # Create your views here. from django import forms # 导入forms组件 # 定义校验规则 class UserForm(forms.Form): name = forms.CharField(min_length=4, max_length=10) email = forms.EmailField() def reg(request): if request.method == 'POST': # 1.form.is_valid() 是否通过验证 form = UserForm({'name': 'alex', 'email': '123@qq.com'}) print(form.is_valid()) # True 返回布尔值 form = UserForm({'name': 'a', 'email': '123'}) print(form.is_valid()) # False form = UserForm({'name': 'alex', 'email': '123@qq.com', 'age': '33'}) print(form.is_valid()) # True # form = UserForm({'name': 'alex', 'xxx': '123@qq.com'}) print(form.is_valid()) # False form = UserForm({'name': 'a', 'email': '123', 'xxx': '123'}) print(form.is_valid()) # False # 2. form.cleaned_data # form.errors if form.is_valid(): print('cleaned_data1:', form.cleaned_data) print('errors1:', form.errors) else: print('cleaned_data2:', form.cleaned_data) print('errors2:', form.errors) # 取出error——msg print(form.errors.get("name")) print(type(form.errors.get("name"))) # ErrorList print(form.errors.get("name")[0]) # Ensure this value has at least 4 characters (it has 1). """ if 所有字段校验成功,则 form.cleaned_data: {'name': 'alex', 'email': '123@qq.com'} 只保留定义过的字段 form.errors: 空 if 校验不成功,则 form.cleaned_data:{'name': 'alex'} 只保留定义过的字段, form.errors: <li>email<ul class="errorlist"> 定义过的字段,未通过的信息 (cleaned_data + errors 之和,必定是定义过的所有字段) """ return HttpResponse('注册成功') return render(request, 'reg.html')
(1)验证通过
验证字段
(2)验证不通过
示例1:验证字段
示例2:验证字段
5、取出 forms.error错误信息
6、完整演示代码
url
from django.urls import path, re_path, include
from app01 import views
urlpatterns = [
re_path(r'reg_test/$', views.reg_test, name='reg_test'),
]
view
from django.shortcuts import render, HttpResponse from django import forms # 导入forms组件 # 定义校验规则 class UserForm(forms.Form): name = forms.CharField(min_length=4, max_length=10) pwd = forms.CharField(min_length=4) _pwd = forms.CharField(min_length=4) email = forms.EmailField() tel = forms.CharField() def reg_test(request): if request.method == "POST": form = UserForm(request.POST) # from表单的name属性值应该与forms组件字段名称一致 print(form) if form.is_valid(): print(form.cleaned_data) return HttpResponse("注册成功") else: print(form.cleaned_data) # {'email': '123@qq.com', 'tel': 'a3456789'} print(form.errors) # <ul class="errorlist"><li>name<ul class="errorlist"><li>This fie print(type(form.errors)) # ErrorList print(form.errors.get('name')) # <ul class="errorlist"><li>This field is required.</li></ul> print(type(form.errors.get('name'))) # ErrorList print(form.errors.get('name')[0]) # This field is required. return HttpResponse("注册失败") return render(request, 'reg.html')
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> {% csrf_token %} <p>用户名 <input type="text" name="user"></p> <p>密码 <input type="password" name="pwd"></p> <p>确认密码 <input type="password" name="_pwd"></p> <p>邮箱 <input type="text" name="email"></p> <p>手机号 <input type="text" name="tel"></p> <input type="submit" value="注册"> </form> </body> </html>
注意点:
from表单的name属性值应该与forms组件字段名称一致
<tr><th><label for="id_name">Name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="name" maxlength="10" minlength="4" required id="id_name" /></td></tr> <tr><th><label for="id_pwd">Pwd:</label></th><td><ul class="errorlist"><li>Ensure this value has at least 4 characters (it has 3).</li></ul><input type="text" name="pwd" value="123" minlength="4" required id="id_pwd" /></td></tr> <tr><th><label for="id__pwd"> pwd:</label></th><td><ul class="errorlist"><li>Ensure this value has at least 4 characters (it has 3).</li></ul><input type="text" name="_pwd" value="123" minlength="4" required id="id__pwd" /></td></tr> <tr><th><label for="id_email">Email:</label></th><td><input type="email" name="email" value="123@qq.com" required id="id_email" /></td></tr> <tr><th><label for="id_tel">Tel:</label></th><td><input type="text" name="tel" value="a3456789" required id="id_tel" /></td></tr>
2、forms组件的渲染标签功能
1、方式1: 用户名 {{ form.name }}
views
from django.shortcuts import render, HttpResponse from django import forms # 导入forms组件 # 定义校验规则 class UserForm(forms.Form): name = forms.CharField(min_length=4, max_length=10) pwd = forms.CharField(min_length=4) r_pwd = forms.CharField(min_length=4) email = forms.EmailField() tel = forms.CharField() def reg_html(request): form = UserForm() return render(request, 'reg_html.html', locals())
reg.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>forms组件渲染方式1</h3> <form action="" method="post"> {% csrf_token %} <p>{{ form.name.label }} {{ form.name }}</p> <p>{{ form.pwd.label }} {{ form.pwd }}</p> <p>{{ form.r_pwd.label }} {{ form.r_pwd }}</p> <p>{{ form.email.label }} {{ form.email }}</p> <p>{{ form.tel.label }} {{ form.tel }}</p> <input type="submit" value="注册"> </form> </body> </html>
原生标签与渲染标签的区别
2、方式2:推荐
views视图
from django.shortcuts import render, HttpResponse # Create your views here. from django import forms # 导入forms组件 # 定义校验规则 class UserForm(forms.Form): name = forms.CharField(min_length=4, max_length=10, label="用户名") pwd = forms.CharField(min_length=4, label="密码") r_pwd = forms.CharField(min_length=4, label="确认密码") email = forms.EmailField(label="邮箱") tel = forms.CharField(label="电话") def reg_html(request): form = UserForm() return render(request, 'reg_html.html', locals())
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>forms组件渲染方式2:推荐</h3> <form action="" method="post"> {% csrf_token %} {% for field in form %} <p><label for="">{{ field.label }}:</label>{{ field }}</p> {% endfor %} </form> </body> </html>
3、方式3: {{ form.as_p }} 不灵活
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>forms组件渲染方式3 </h3> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <hr> {{ form.as_ul }} <hr> {{ form.as_table }} </form> </body> </html>
3、显示error与重置输入信息功能
views视图
from django.shortcuts import render, HttpResponse # Create your views here. from django import forms # 导入forms组件 # 定义校验规则 class UserForm(forms.Form): name = forms.CharField(min_length=4, max_length=10, label="用户名") pwd = forms.CharField(min_length=4, label="密码") r_pwd = forms.CharField(min_length=4, label="确认密码") email = forms.EmailField(label="邮箱") tel = forms.CharField(label="电话") def reg_html(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, 'reg_html.html', locals()) form = UserForm() return render(request, 'reg_html.html', locals())
html
novalidate 当提交表单时不对表单数据(输入)进行验证
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>forms组件渲染方式1</h3> {# novalidate 当提交表单时不对表单数据(输入)进行验证#} <form action="" method="post" novalidate> {% csrf_token %} <p>{{ form.name.label }} {{ form.name }} <span>{{ form.name.errors.0 }}</span></p> <p>{{ form.pwd.label }} {{ form.pwd }} <span>{{ form.pwd.errors.0 }}</span></p> <p>{{ form.r_pwd.label }} {{ form.r_pwd }} <span>{{ form.r_pwd.errors.0 }}</span></p> <p>{{ form.email.label }} {{ form.email }} <span>{{ form.email.errors.0 }}</span></p> <p>{{ form.tel.label }} {{ form.tel }} <span>{{ form.tel.errors.0 }}</span></p> <input type="submit" value="注册"> </form> </body> </html>
4、forms组件的参数配置
forms组件 代码
from django.shortcuts import render, HttpResponse # Create your views here. from django import forms # 导入forms组件 from django.forms import widgets # HTML Widget classes # 定义校验规则 class UserForm(forms.Form): name = forms.CharField(min_length=4, max_length=10, label="用户名", error_messages={'required': '该字段不能为空', 'min_length': '不能少于4个字符'}, # widget=widgets.TextInput(), # 定制Html控件 widget=widgets.TextInput(attrs={'class': 'form-control'}), # html控件添加样式 ) pwd = forms.CharField(min_length=4, label="密码", # widget=widgets.PasswordInput(), # 定制Html控件 widget=widgets.PasswordInput(attrs={'class': 'form-control'}), error_messages={'required': '该字段不能为空'}, ) r_pwd = forms.CharField(min_length=4, label="确认密码", error_messages={'required': '该字段不能为空'}, widget=widgets.PasswordInput(attrs={'class': 'form-control'}), ) email = forms.EmailField(label="邮箱", error_messages={'required': '该字段不能为空', 'invalid': '格式错误'}, widget=widgets.EmailInput(attrs={'class': 'form-control'}) ) tel = forms.CharField(label="电话", error_messages={'required': '该字段不能为空 '}, widget=widgets.TextInput(attrs={'class': 'form-control'}) ) def reg_html(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, 'reg_html.html', locals()) form = UserForm() return render(request, 'reg_html.html', locals())
加入bootstrap后的 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"> <style type="text/css"> span{ color: red; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6 col-lg-offset-3"> <h3>forms组件渲染方式1</h3> {# novalidate 当提交表单时不对表单数据(输入)进行验证#} <form action="" method="post" novalidate> {% csrf_token %} <p>{{ form.name.label }} {{ form.name }} <span>{{ form.name.errors.0 }}</span></p> <p>{{ form.pwd.label }} {{ form.pwd }} <span>{{ form.pwd.errors.0 }}</span></p> <p>{{ form.r_pwd.label }} {{ form.r_pwd }} <span>{{ form.r_pwd.errors.0 }}</span></p> <p>{{ form.email.label }} {{ form.email }} <span>{{ form.email.errors.0 }}</span></p> <p>{{ form.tel.label }} {{ form.tel }} <span>{{ form.tel.errors.0 }}</span></p> <input type="submit" value="注册"> </form> </div> </div> </div> </body> </html>
5、forms组件的局部钩子
1、ValidationError:验证错误
models
from django.db import models 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)
froms组件,如何进行验证错误?
from app01.models import UserInfo # 导入user表 from django.core.exceptions import ValidationError # 导入验证错误 from django import forms # 导入forms组件 from django.forms import widgets # HTML Widget classes # 定义校验规则 class UserForm(forms.Form): name = forms.CharField(min_length=4, max_length=10, label="用户名", error_messages={'required': '该字段不能为空', 'min_length': '不能少于4个字符'}, # widget=widgets.TextInput(), # 定制Html控件 widget=widgets.TextInput(attrs={'class': 'form-control'}), # html控件添加样式 ) pwd = forms.CharField(min_length=4, label="密码", # widget=widgets.PasswordInput(), # 定制Html控件 widget=widgets.PasswordInput(attrs={'class': 'form-control'}), error_messages={'required': '该字段不能为空'}, ) r_pwd = forms.CharField(min_length=4, label="确认密码", error_messages={'required': '该字段不能为空'}, widget=widgets.PasswordInput(attrs={'class': 'form-control'}), ) email = forms.EmailField(label="邮箱", error_messages={'required': '该字段不能为空', 'invalid': '格式错误'}, widget=widgets.EmailInput(attrs={'class': 'form-control'}) ) tel = forms.CharField(label="电话", error_messages={'required': '该字段不能为空 '}, widget=widgets.TextInput(attrs={'class': 'form-control'}) ) # 验证用户名 def clean_name(self): val = self.cleaned_data.get("name") # 获取清洗后的字段中的name ret = UserInfo.objects.filter(name=val) # 数据库中的user if not ret: return ret else: raise ValidationError('该用户已经注册') # 验证错误
forms组件源码
vies视图中
def reg_html(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, 'reg_html.html', locals()) form = UserForm() return render(request, 'reg_html.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"> <style type="text/css"> span{ color: red; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6 col-lg-offset-3"> <h3>forms组件渲染方式1</h3> {# novalidate 当提交表单时不对表单数据(输入)进行验证#} <form action="" method="post" novalidate> {% csrf_token %} <p>{{ form.name.label }} {{ form.name }} <span>{{ form.name.errors.0 }}</span></p> <p>{{ form.pwd.label }} {{ form.pwd }} <span>{{ form.pwd.errors.0 }}</span></p> <p>{{ form.r_pwd.label }} {{ form.r_pwd }} <span>{{ form.r_pwd.errors.0 }}</span></p> <p>{{ form.email.label }} {{ form.email }} <span>{{ form.email.errors.0 }}</span></p> <p>{{ form.tel.label }} {{ form.tel }} <span>{{ form.tel.errors.0 }}</span></p> <input type="submit" value="注册"> </form> </div> </div> </div> </body> </html>
2、校验方法:clean_name 源码
_clean_fields 方法的源码
def _clean_fields(self): for name, field in self.fields.items(): # {"name": name规则对象,"pwd": pwd规则对象...} # value_from_datadict() gets the data from the data dictionaries. # Each widget type knows how to retrieve its own data, because some # widgets split data over several HTML fields. if field.disabled: value = self.get_initial_for_field(field, name) else: value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name)) try: if isinstance(field, FileField): initial = self.get_initial_for_field(field, name) value = field.clean(value, initial) else: value = field.clean(value) # 按照规则对象校验传递进来的数据 self.cleaned_data[name] = value if hasattr(self, 'clean_%s' % name): value = getattr(self, 'clean_%s' % name)() self.cleaned_data[name] = value # 执行 def clean_name(self): except ValidationError as e: self.add_error(name, e)
3、局部钩子函数如何校验
1、forms代码:校验name,tel
from app01.models import UserInfo # 导入user表 from django.core.exceptions import ValidationError # 导入验证错误 from django import forms # 导入forms组件 from django.forms import widgets # HTML Widget classes # 定义校验规则 class UserForm(forms.Form): name = forms.CharField(min_length=4, max_length=10, label="用户名", error_messages={'required': '该字段不能为空', 'min_length': '不能少于4个字符'}, # widget=widgets.TextInput(), # 定制Html控件 widget=widgets.TextInput(attrs={'class': 'form-control'}), # html控件添加样式 ) pwd = forms.CharField(min_length=4, label="密码", # widget=widgets.PasswordInput(), # 定制Html控件 widget=widgets.PasswordInput(attrs={'class': 'form-control'}), error_messages={'required': '该字段不能为空'}, ) r_pwd = forms.CharField(min_length=4, label="确认密码", error_messages={'required': '该字段不能为空'}, widget=widgets.PasswordInput(attrs={'class': 'form-control'}), ) email = forms.EmailField(label="邮箱", error_messages={'required': '该字段不能为空', 'invalid': '格式错误'}, widget=widgets.EmailInput(attrs={'class': 'form-control'}) ) tel = forms.CharField(label="电话", error_messages={'required': '该字段不能为空 '}, widget=widgets.TextInput(attrs={'class': 'form-control'}) ) # 验证用户名 def clean_name(self): val = self.cleaned_data.get("name") # 获取清洗后的字段中的name ret = UserInfo.objects.filter(name=val) # 数据库中的user if not ret: return ret else: raise ValidationError('该用户已经注册') # 验证错误 # 验证手机号 def clean_tel(self): val = self.cleaned_data.get("tel") if len(val) == 11: return val else: raise ValidationError("手机号格式错误")
示例1:校验错误
示例2:校验正确
4、全局钩子校验
1、全局钩子clean 源码剖析
2、直接覆盖父类的clean方法,全局钩子
froms组件继承的是BaseFrom类,所以可以直接覆盖父类的clean方法,进行全局钩子校验
views视图
from django.shortcuts import render, HttpResponse from app01.models import UserInfo # 导入user表 from django.core.exceptions import ValidationError # 导入验证错误 from django import forms # 导入forms组件 from django.forms import widgets # HTML Widget classes # 定义校验规则 class UserForm(forms.Form): name = forms.CharField(min_length=4, max_length=10, label="用户名", error_messages={'required': '该字段不能为空', 'min_length': '不能少于4个字符'}, # widget=widgets.TextInput(), # 定制Html控件 widget=widgets.TextInput(attrs={'class': 'form-control'}), # html控件添加样式 ) pwd = forms.CharField(min_length=4, label="密码", # widget=widgets.PasswordInput(), # 定制Html控件 widget=widgets.PasswordInput(attrs={'class': 'form-control'}), error_messages={'required': '该字段不能为空'}, ) r_pwd = forms.CharField(min_length=4, label="确认密码", error_messages={'required': '该字段不能为空'}, widget=widgets.PasswordInput(attrs={'class': 'form-control'}), ) email = forms.EmailField(label="邮箱", error_messages={'required': '该字段不能为空', 'invalid': '格式错误'}, widget=widgets.EmailInput(attrs={'class': 'form-control'}) ) tel = forms.CharField(label="电话", error_messages={'required': '该字段不能为空 '}, widget=widgets.TextInput(attrs={'class': 'form-control'}) ) # 直接覆盖父类的clean方法, 全局钩子 def clean(self): pwd = self.cleaned_data.get("pwd") r_pwd = self.cleaned_data.get("r_pwd") if pwd == r_pwd: return self.cleaned_data else: raise ValidationError("两次密码不一致") def reg_html(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): print(form.cleaned_data) # {"name": "alex", "pwd": "123",...} else: print(form.cleaned_data) # # 所有清洗的字段以及对应的值 print(form.errors) # ErrorDict: {"校验错误的字段":["错误信息"]} print(form.errors.get('name')) # ErrorList {'错误信息',} # 获取全局钩子的error print("error:", form.errors.get("__all__")[0]) errors = form.errors.get("__all__") return render(request, 'reg_html.html', locals()) form = UserForm() return render(request, 'reg_html.html', locals())
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"> <style type="text/css"> span{ color: red; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6 col-lg-offset-3"> <h3>forms组件渲染方式1</h3> {# novalidate 当提交表单时不对表单数据(输入)进行验证#} <form action="" method="post" novalidate> {% csrf_token %} <p>{{ form.name.label }} {{ form.name }} <span>{{ form.name.errors.0 }}</span></p> <p>{{ form.pwd.label }} {{ form.pwd }} <span>{{ form.pwd.errors.0 }}</span></p> {# <p>{{ form.r_pwd.label }} {{ form.r_pwd }} <span>{{ form.r_pwd.errors.0 }}</span></p> 局部钩子错误#} <p>{{ form.r_pwd.label }} {{ form.r_pwd }} <span class="pull-right error">{{ errors.0 }}</span></p> <p>{{ form.email.label }} {{ form.email }} <span>{{ form.email.errors.0 }}</span></p> <p>{{ form.tel.label }} {{ form.tel }} <span>{{ form.tel.errors.0 }}</span></p> <input type="submit" value="注册"> </form> </div> </div> </div> </body> </html>
重点
# 接收全局钩子error errors.0 # bootstarp样式 <span class="pull-right error"> <p>{{ form.r_pwd.label }} {{ form.r_pwd }} <span class="pull-right error">{{ errors.0 }}</span></p>
5、密码,确认密码,顺序
# 每个字段校验完,在走全局方法 比如,先判断密码是否正确,符合规则再判断,两次密码是否一致
如果没有pwd传入进来的话,
# 直接覆盖父类的clean方法, 全局钩子 def clean(self): pwd = self.cleaned_data.get("pwd") r_pwd = self.cleaned_data.get("r_pwd") # 先判断是否接受到pwd,r_pwd的值 if pwd and r_pwd: if pwd == r_pwd: return self.cleaned_data else: raise ValidationError("两次密码不一致") else: return self.cleaned_data
6、form.is_valid 调用源码
form.is_valid def is_valid(self): """Return True if the form has no errors, or False otherwise.""" return self.is_bound and not self.errors def errors(self): """Return an ErrorDict for the data provided for the form.""" if self._errors is None: self.full_clean() return self._errors def full_clean(self): """ Clean all of self.data and populate self._errors and self.cleaned_data. """ self._errors = ErrorDict() if not self.is_bound: # Stop further processing. return self.cleaned_data = {} # If the form is permitted to be empty, and none of the form data has # changed from the initial data, short circuit any validation. if self.empty_permitted and not self.has_changed(): return self._clean_fields() # 校验每一个字段 self._clean_form() # 校验全部字段 self._post_clean()
# 局部钩子 def _clean_fields(self): for name, field in self.fields.items(): # 校验每一个字段 # value_from_datadict() gets the data from the data dictionaries. # Each widget type knows how to retrieve its own data, because some # widgets split data over several HTML fields. if field.disabled: value = self.get_initial_for_field(field, name) else: value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name)) try: if isinstance(field, FileField): initial = self.get_initial_for_field(field, name) value = field.clean(value, initial) else: value = field.clean(value) self.cleaned_data[name] = value if hasattr(self, 'clean_%s' % name): value = getattr(self, 'clean_%s' % name)() self.cleaned_data[name] = value except ValidationError as e: self.add_error(name, e)
# 全局钩子调用顺序 def _clean_form(self): try: cleaned_data = self.clean() # 全局钩子 except ValidationError as e: self.add_error(None, e) else: if cleaned_data is not None: self.cleaned_data = cleaned_data def clean(self): """ Hook for doing any extra form-wide cleaning after Field.clean() has been called on every field. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field named '__all__'. """ return self.cleaned_data @html_safe class BaseForm: """ The main implementation of all the Form logic. Note that this class is different than Form. See the comments by the Form class for more info. Any improvements to the form API should be made to this class, not to the Form class. """ def clean(self): pass
7、总结:forms组件解耦,调用冲突
myforms.py 组件代码
from app01.models import UserInfo # 导入user表 from django.core.exceptions import ValidationError # 导入验证错误 from django import forms # 导入forms组件 from django.forms import widgets # HTML Widget classes # 定义校验规则 class UserForm(forms.Form): name = forms.CharField(min_length=4, max_length=10, label="用户名", error_messages={'required': '该字段不能为空', 'min_length': '不能少于4个字符'}, # widget=widgets.TextInput(), # 定制Html控件 widget=widgets.TextInput(attrs={'class': 'form-control'}), # html控件添加样式 ) pwd = forms.CharField(min_length=4, label="密码", # widget=widgets.PasswordInput(), # 定制Html控件 widget=widgets.PasswordInput(attrs={'class': 'form-control'}), error_messages={'required': '该字段不能为空'}, ) r_pwd = forms.CharField(min_length=4, label="确认密码", error_messages={'required': '该字段不能为空'}, widget=widgets.PasswordInput(attrs={'class': 'form-control'}), ) email = forms.EmailField(label="邮箱", error_messages={'required': '该字段不能为空', 'invalid': '格式错误'}, widget=widgets.EmailInput(attrs={'class': 'form-control'}) ) tel = forms.CharField(label="电话", error_messages={'required': '该字段不能为空 '}, widget=widgets.TextInput(attrs={'class': 'form-control'}) ) # 验证用户名 def clean_name(self): val = self.cleaned_data.get("name") # 获取清洗后的字段中的name ret = UserInfo.objects.filter(name=val) # 数据库中的user if not ret: return ret 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): pwd = self.cleaned_data.get("pwd") r_pwd = self.cleaned_data.get("r_pwd") # 先判断是否接受到pwd,r_pwd的值 if pwd and r_pwd: if pwd == r_pwd: return self.cleaned_data else: raise ValidationError("两次密码不一致") else: return self.cleaned_data
url
from django.urls import path, re_path, include from app01 import views urlpatterns = [ re_path(r'reg_html/$', views.reg_html, name='reg_html'), ]
views视图代码
from django.shortcuts import render from app01.myforms import * def reg_html(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): print(form.cleaned_data) # {"name": "alex", "pwd": "123",...} else: print(form.cleaned_data) # # 所有清洗的字段以及对应的值 print(form.errors) # ErrorDict: {"校验错误的字段":["错误信息"]} print(form.errors.get('name')) # ErrorList {'错误信息',} # 获取全局钩子的error # print("error:", form.errors.get("__all__")[0]) errors = form.errors.get("__all__") return render(request, 'reg_html.html', locals()) form = UserForm() return render(request, 'reg_html.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"> <style type="text/css"> span{ color: red; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6 col-lg-offset-3"> <h3>forms组件渲染方式1</h3> {# novalidate 当提交表单时不对表单数据(输入)进行验证#} <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.label }} {{ form.r_pwd }} <span>{{ form.r_pwd.errors.0 }}</span></p> #} {# 全局钩子错误#}<p>{{ form.r_pwd.label }} {{ form.r_pwd }} <span class="pull-right error">{{ errors.0 }}</span></p> <p>{{ form.email.label }} {{ form.email }} <span class="pull-right error">{{ form.email.errors.0 }}</span></p> <p>{{ form.tel.label }} {{ form.tel }} <span class="pull-right error">{{ form.tel.errors.0 }}</span></p> <input type="submit" value="注册"> </form> </div> </div> </div> </body> </html>