django Form元件校驗流程

龙岩龙發表於2024-09-03

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})

相關文章