簡單的例子:用戶輸入用戶名和密碼後登錄系統,這裏暫時不連接數據庫。系統驗證登錄成功,直接跳轉到百度的首頁。登錄失敗,系統會將錯誤信息打印在頁面上。
1. 登錄模板
模板中需要寫個簡單的登錄表單,如下面的:
<form action="/login/" method="POST" name="loginForm">
<div class="form-group">
<label for="name">用戶名</label> <input type="text" class="form-control" name="username" placeholder="請輸入用戶名">
</div>
<div class="form-group">
<label for="">密碼</label> <input type="password" class="form-control" name="pwd" placeholder="請輸入密碼">
<div style="color: red;font-weight: bold">{{ msg }}</div>
</div>
<button type="submit" class="btn btn-primary" onclick="return checkForm()">登錄</button>
</form>
模板中的 {{ msg }}
,
2. 登錄邏輯
from django.urls import path
from django.shortcuts import HttpResponse, render, redirect
def login(request): #
'''
處理用戶請求,返回相響應結果
:param request:用戶請求的相關信息(不是字節,是對象)
:return:
'''
if request.method == 'GET':
return render(request, 'login.html') # 本質上是調用HttpResponse,自動找到login.html文件,讀取內容並返回給用戶
else:
# print(request.POST) # 用戶POST提交的數據(請求體)<QueryDict: {'name': ['thanlon'], 'pwd': ['123']}>
# user = request.POST['username']#直接索引,如果沒有username會報錯
username = request.POST.get('username') # 如果沒有username不會報錯,返回None
pwd = request.POST.get('pwd') # 如果沒有username不會報錯,返回None
if username == 'thanlon' and pwd == '123456':
return redirect('https://www.blueflags.cn')
else:
return render(request, 'login.html', {'msg': '用戶名或密碼錯誤!'}) # django內部做模板渲染
urlpatterns = [
# path('admin/', admin.site.urls),
path('login/', login),
]
3. 結論
用戶名和密碼輸入正確後,則登錄成功跳轉百度首頁。否則,登錄失敗系統會將錯誤信息放到登錄模板,然後傳給用戶。表現上是刷新表單界面,顯示提示信息: