利用表单验证类进行验证
??当用户提交表单时,往往需要进行验证,再进行保存至数据库,例如下图的注册表单,这时我们就可以利用Django的表单验证类。 ??表单验证类 ??自定义表单验证类需要继承Django的forms. Form基类,验证字段函数名称为clean_字段,验证通过需要返回,最后到clean()验证方法结束验证,这里通过原生的正则表达式进行了电话、密码以及邮箱验证。
from django import forms
from ..models.users import Users
import re
class RegisterForm(forms.Form):
username = forms.CharField(max_length=32, error_messages={"required": '用户名不能为空'})
email = forms.CharField(error_messages={"required": '邮箱不能为空'})
telephone = forms.CharField(error_messages={"required": '手机不能为空'})
password = forms.CharField(error_messages={"required": '密码不能为空'})
password_confirm = forms.CharField(error_messages={"required": "确认密码不能为空"})
def clean_username(self):
username = self.cleaned_data.get('username')
if not re.match(r'[0-9a-zA-Z]{4,10}', username):
raise forms.ValidationError('用户名格式不正确')
ret = Users.objects.filter(username=username)
if ret:
raise forms.ValidationError("用户名已经存在")
return username
def clean_email(self):
email = self.cleaned_data.get('email')
if not re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$', email):
raise forms.ValidationError("邮箱格式不正确")
return email
def clean_telephone(self):
telephone = self.cleaned_data.get('telephone')
if not re.match(r"^1[35678]\d{9}$", telephone):
raise forms.ValidationError("手机格式不正确")
return telephone
def clean_password(self):
password = self.cleaned_data.get('password')
if not re.match(r'[0-9a-zA-Z]{6,16}', password):
raise forms.ValidationError('密码格式不正确')
return password
def clean(self):
clean_data = super().clean()
password = self.cleaned_data.get('password')
password_confirm = self.cleaned_data.get('password_confirm')
if password != password_confirm:
raise forms.ValidationError('两次输入密码不一致')
return clean_data
??表单验证 ??表单通常都是通过post方法提交,即把request. POST传入表单验证类进行验证,通过is_valid()判断验证是否通过,没有错误就进行下一步操作,否则通过获取错误进行返回。
from django.shortcuts import render
from django.http import JsonResponse
from django.views import View
from home.forms import RegisterForm
from home.models import Users
from home.tools import md5_
import random
class RegisterView(View):
def get(self, request):
return render(request, 'home/user/register.html', {'nav_list': 7, 'code': 200})
def post(self, request):
form = RegisterForm(request.POST)
if form.is_valid():
interfere = random.randint(10000, 99999)
username = form.cleaned_data.get('username')
password = md5_(form.cleaned_data.get('password') + str(interfere))
email = form.cleaned_data.get('email')
telephone = form.cleaned_data.get('telephone')
Users(username=username, password=password, email=email, telephone=telephone, interfere=interfere).save()
return JsonResponse({"msg": '注册成功', "code": 200})
else:
for error in form.errors.get_json_data().values():
return JsonResponse({'msg': error[0].get('message'), 'code': 201})
|