form表单 Django验证处理 自定义验证密码
程序员文章站
2022-03-07 19:44:43
...
form主要完成验证功能和生成HTML代码
继承创建类
from django import forms
from django.forms import fields
class F1form(forms.Form):
显示
HTML
修改
html
添加
HTML
form 与 ajax 交互验证
HTML页面
自定义密码
登录,注册
- 密码:数字,字母,特殊字符
- 密码两次输入一致
提交:
v = MyForm(request.GET) # 6个字段
if v.is_valid():
pass
密码示例:RegexField自定义密码验证规则
password = forms.RegexField(
'^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[aaa@qq.com#$\%\^\&\*\(\)])[aaa@qq.com#$\%\^\&\*\(\)]{8,32}$',
min_length=12,
max_length=32,
error_messages={'required': '密码不能为空.',
'invalid': '密码必须包含数字,字母、特殊字符',
'min_length': "密码长度不能小于8个字符",
'max_length': "密码长度不能大于32个字符"}
)
class RegisterForm(BaseForm, django_forms.Form):
username = django_fields.CharField()
password = django_fields.CharField()
confirm_pwd = django_fields.CharField()
def clean(self):
v1 = self.cleaned_data['password']
v2 = self.cleaned_data['confirm_pwd']
if v1 == v2:
pass
else:
from django.core.exceptions import ValidationError
raise ValidationError('密码输入不一致')
def register(request):
v = RegisterForm(request.POST)
if v.is_valid():
pass
else:
v.errors['username']
v.errors['__all__']
v.errors[NON_FIELD_ERRORS]
{
__all__: [],
username: [],
password: []
confirm_pwd: []
}
return render(request, 'register.html', {'v':v})
register.html
{{v.errors.username.0}}
{{v.non_field_errors}}