django中Form组件字段校验顺序:先字段内部校验,然后钩子方法校验:
from django.shortcuts import render, redirect
from django.core.validators import RegexValidator
from django import forms
from app01.utilss.mdy import md
from app01.models import Administrator, Customer
定义登录表单
class SmsLogin(forms.Form):
username = forms.CharField(
label="用户名",
min_length=6,
widget=forms.TextInput(attrs={"class": "input", "id": "email", "placeholder": "输入账户"}),
error_messages={
"min_length": "用户名至少6位",
"required": "用户名不能为空",
"invalid": "用户名格式不正确"
},
required=True,
validators=[RegexValidator(r'\d+\w+', '格式不正确')]
)
password = forms.CharField(
label="密码",
max_length=8,
widget=forms.PasswordInput(attrs={"class": "input", "id": "password", "placeholder": "输入密码"}),
error_messages={
"max_length": "最多八位",
"required": "密码不能为空",
"invalid": "密码格式不正确"
},
required=True,
validators=[RegexValidator(r'\d+\w+', '格式不正确')]
)
def clean_username(self):
# 校验成功
self.cleaned_data['username'] = self.cleaned_data['username'].strip().lower()
#返回字段
return self.cleaned_data['username']
登出视图
def login(request):
if 'user' in request.session:
del request.session['user']
return render(request, 'login.html')
短信登录视图
def smslogin(request):
if request.method == "GET":
form = SmsLogin()
# 检查用户是否已经登录,如果是则重定向到管理员主页
if request.session.get("user"):
return redirect('/home/admin/')
return render(request, 'smslogin.html', {"form": form})
# 处理POST请求
form = SmsLogin(request.POST)
if not form.is_valid():
return render(request, 'smslogin.html', {"form": form})
# 获取验证后的数据
username = form.cleaned_data['username']
password = form.cleaned_data['password']
# 检查管理员表中是否存在匹配的用户
admin_user = Administrator.objects.filter(code=1, username=username, password=md(password)).first()
if admin_user:
request.session["user"] = {"isadmin": True, "username": username}
return redirect('/home/admin/')
# 检查客户表中是否存在匹配的用户
customer_user = Customer.objects.filter(code=1, username=username, password=md(password)).first()
if customer_user:
request.session["user"] = {"isadmin": False, "username": username}
return redirect('/home/admin/')
# 如果都没有匹配的记录,则返回错误信息
return render(request, 'smslogin.html', {'form': form, 'error': "用户名或密码错误"})
管理员主页视图
def admin(request):
if request.method == "GET":
username = request.session.get("user", {}).get("username", "")
return render(request, 'home.html', {"name": username})