python測試開發django-26.表單提交之post登錄案例


前言

注冊和登錄功能實現都是post請求接口,只不過注冊是往數據庫插入數據,登錄是從數據庫里面查詢數據。
本篇接着上一篇寫個簡單的登錄頁面請求,用戶注冊時密碼加密存儲,用戶登錄時候對輸入的密碼校驗。

登錄頁面

templates/login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登錄頁面</title>
</head>
<body>
<h1>歡迎登錄!</h1>
<form action="/" method="post">
    {% csrf_token %}
      <p>
        用戶名:<input type="text" id="id_username" name="username", required="required"> *
      </p>
      <p>
         密碼:<input type="text" id="id_username" name="password", required="required"> *
    </p>

    <p>
          <input type="submit" value="登錄">
    </p>
</form>

</body>
</html>

視圖與urls

查詢數據庫用戶名和密碼

# views.py
from django.shortcuts import render
from hello.models import User
from django.http import HttpResponse

# Create your views here.
def login(request):
    '''登錄頁面'''
    if request.method == "GET":
        return render(request, 'login.html')
    if request.method == "POST":
        # 先查詢數據庫是否有此用戶名
        username = request.POST.get('username')
        psw = request.POST.get('password')
        # 查詢用戶名和密碼
        user_obj = User.objects.filter(user_name=username, psw=psw).first()
        if user_obj:
            return HttpResponse('登陸成功')
        else:
            return HttpResponse('用戶名或密碼錯誤')

urls.py訪問地址

from django.conf.urls import url
from hello import views

urlpatterns = [
    # 新增用戶
    url(r'^register/', views.register),
    url(r'^login/', views.login),
]

密碼加密make_password

密碼如果明文存儲到數據庫的話不太安全,一般會加密存儲,django里面提供了一套加密方法make_password,解密用check_password,需先導入

from django.contrib.auth.hashers import make_password, check_password

views.py里面寫入數據庫時,加個make_password方法轉下就行了

# 寫入數據
user = User()
user.user_name = username
user.psw = make_password(psw) # 加密存儲
user.mail = mail
user.save()

重新注冊,存入的psw數據就是加密后的了

校驗密碼check_password

登錄的時候,我們需要校驗用戶對應的密碼,由於前面加密存儲密碼了,校驗的時候,先獲取用戶輸入的密碼,然后讀取數據庫對應用戶密碼
再通過check_password函數校驗密碼,密碼一致返回True, 不一致返回False。

# views.py
from django.shortcuts import render
from hello.models import User
from django.http import HttpResponse


def login(request):
    '''登錄頁面'''
    if request.method == "GET":
        return render(request, 'login.html')
    if request.method == "POST":
        # 先查詢數據庫是否有此用戶名
        username = request.POST.get('username')
        psw = request.POST.get('password')

        # 查詢用戶名對應的密碼
        ret = User.objects.filter(user_name=username).first()
        # 校驗密碼
        is_psw_true = check_password(psw, ret.psw)
        if is_psw_true:
            return HttpResponse('登陸成功')
        else:
            return HttpResponse('用戶名或密碼錯誤')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM