表單登陸模版 <form action='' method='POST'> 用戶名:<input name='username'></input></br> 密 碼:<input name='password'></input> </br> <input type='submit' value='提交'> <div style="color:red ">{{status}}</div> #登陸狀態返回值 </form>
1、判斷登陸帳戶,首先要從表單中獲取輸入的數據,此時HTTP提交請求爲POSThtml
if request.method=='POST': #若是HTTP請求爲POST username=request.POST.get('username') #獲取輸入的username的值 password=request.POST.get('password') #獲取輸入 的password的值
2、判斷輸入內容是否合法python
is_empty=all([username,password]) #用all()函數判斷2個值是否爲真,若是兩個都爲真(不爲空) if is_empty: #若是不爲空,則判斷賬號和密碼是否合法 count=UserInfo.objects.filter(username=username,password=password).count() if count==1: return redirect('/system/index') #若是都正確,則跳轉到 /system/index/ else: ret['status']='用戶名或密碼錯誤' else: ret['status']='用戶名或密碼不能爲空'
整個登陸函數:django
首先有個提醒的登陸狀態顯示字典,ret={'status':''}函數
return render(request,'login.html',ret) #不管是否爲POST或GET,都返回Login 和用戶狀態url
from django.shortcuts import render,redirect from system.models import BookInfo,Group,UserInfo def login(request): ret={'status':''} #設置狀態 if request.method=='POST': #若是HTTP請求爲POST username=request.POST.get('username') #獲取輸入的username的值 password=request.POST.get('password') #獲取輸入 的password的值 is_empty=all([username,password]) #用all()函數判斷2個值是否都爲真若是兩個都爲真(不爲空) if is_empty: count=UserInfo.objects.filter(username=username,password=password).count() if count==1: #若是不爲空,則判斷用戶名和密碼是否合法 return redirect('/system/index') else: ret['status']='用戶名或密碼錯誤' else: ret['status']='用戶名或密碼不能爲空' return render(request,'login.html',ret) #不管是否爲POST或GET,都返回Login 和用戶狀態
注意:1.使用redirect() 函數,須要導入 redirect 模塊
2.redirect('/system/login/') 括號裏面的 '/' 必需要填spa
這個/ 至關於 url ip 和端口號 ,如127.0.0.1:8000/
3.redirect() 括號裏面只能填 url路徑 ,不能填寫xxx.htmlcode