[oldboy-django][2深入django]form表单clean_xx, clean完成数据验证+ form错误信息

时间:2023-03-08 15:59:14
[oldboy-django][2深入django]form表单clean_xx, clean完成数据验证+ form错误信息

form后台生成form里面的Input标签,以及设置Input的属性

# 需求 后台生成form里面的input标签,并设置input标签的属性,
class RegisterForm(Form):
email = fields.EmailField()
password = fields.CharField()
password2 = fields.CharField()
code = fields.CharField()
avatar = fields.FileField(widget=widgets.FileInput(attrs={'id': 'inputAvatar'})) def register(request):
if request.method == 'GET':
obj = RegisterForm()
return render(request, 'register.html', {'obj': obj}) <form method="POST" action="/register/" enctype="multipart/form-data">
{% csrf_token %}
{{ obj.avatar }}
{{ obj.usernam }}
</form>

向在form里面获取session值,即传递request参数

# form标签向获取request里面的值--重写__init__函数
def __init__(self, request, *args, **kwargs):
self.request = request
super(RegisterForm, self).__init__(*args, **kwargs)

form验证某个字段 self.clean_字段名

# form标签验证某个字段
def clean_code(self):
input_code = self.cleaned_data.get('code')
session_code = self.request.session.get('code') # 请查看check_code函数
if input_code != session_code:
raise ValidationError('验证码错误')
else:
return input_code
# self.errors = {'code': ['验证码错误'], 'xx':[错误1,错误2]}

form验证多个字段 self.clean

# form标签联合数据验证
def clean(self):
"""
此时,已经拿到所有的input值,对两次输入密码进行验证
"""
p1 = self.cleaned_data.get('password1')
p2 = self.cleaned_data.get('password2')
if p1 != p2:
raise ValidationError('两次输入密码不一致') # 默认放到self.errors['__all__']里面
else:
return self.cleaned_data
# return None
"""
self.errors = {'__all__': ['两次输入密码不一致'], 'xx':[错误1,错误2]}
NON_FIELD_ERRORS = '__all__' 前台获取需要用到
此时前端获取该错误; obj.non_field_errors
"""

form验证多个字段 self.clean 指明错误信息的Key,方便前端使用

# 对整体错误的其他设置
def clean(self): if p1 != p2:
self.add_error('password2', '两次输入密码不一致')
# 此时不用抛出异常了,因为抛出异常
# 抛出异常也是执行self.add_error
return None
else:
return self.cleaned_data 此时在前端显示该错误: obj.errors.password2

form 的错误信息self.errors

# form标签数据验证错误信息
self.errors = {'username':[错误1, 错误2], 'password': [错误1, 错误2]}
def clean_xx(self) 如果遇到错,放到self.errors['xx']里面
def clean(self) 如果遇到错,放到self.errors['__all__']里面 但是如果要前端获取self.errors['__all__']错误,obj.errors.__all__是拿不到的
而是obj.non_field_errors, 不是self.errors.non_fields_errors

注册form

# 完整的forms.py
# -*- coding: utf-8 -*-
from django.forms import Form, fields, widgets
from django.core.exceptions import ValidationError class RegisterForm(Form):
username = fields.CharField(widget=widgets.TextInput(
attrs={'class': "form-control"}
))
password = fields.CharField(widget=widgets.PasswordInput(
attrs={'class': "form-control"}
))
password2 = fields.CharField(widget=widgets.PasswordInput(
attrs={'class': "form-control"}
))
code = fields.CharField(widget=widgets.TextInput(
attrs={'class': "form-control"}
))
avatar = fields.FileField(widget=widgets.FileInput(attrs={'id': 'inputAvatar'})) def __init__(self, request, *args, **kwargs):
self.request = request
super(RegisterForm, self).__init__(*args, **kwargs) def clean_code(self):
input_code = self.cleaned_data.get('code').upper()
session_code = self.request.session.get('code').upper() # 请查看check_code函数
if input_code != session_code:
raise ValidationError('验证码错误')
else:
return input_code
# self.errors = {'code': ['验证码错误'], 'xx':[错误1,错误2]} def clean(self):
"""
此时,已经拿到所有的input值,对两次输入密码进行验证
"""
p1 = self.cleaned_data.get('password')
p2 = self.cleaned_data.get('password2')
if p1 != p2:
self.add_error('password2', '两次输入密码不一致') # 此时不用抛出异常了,因为抛出异常
# 抛出异常也是执行self.add_error
return None
# raise ValidationError('两次输入密码不一致')
# 默认放到self.errors['__all__']里面
# 执行的是self.add_error('__all__', '两次输入密码不一致')
else:
return self.cleaned_data """
self.errors = {'__all__': ['两次输入密码不一致'], 'xx':[错误1,错误2]}
NON_FIELD_ERRORS = '__all__' 前台获取需要用到
"""