django的登錄注冊系統(tǒng)

摘要

django框架本身自帶有登錄注冊,也可以自己寫登錄注冊,下面將介紹這這2種方式實(shí)登錄注冊

一、自己寫登錄注冊登出

1.注冊regist

注冊采用的是form表單,提交到數(shù)據(jù)庫,在登錄的時(shí)候,查詢數(shù)據(jù)看,看用戶有沒有注冊,如果用戶沒有注冊,則返回注冊頁面注冊
(1)models.py文件里創(chuàng)建相關(guān)的字段: 用戶名字/用戶密碼/cookies攜帶的ticket

from django.db import models

# Create your models here.

class Users(models.Model):
    u_name = models.CharField(max_length=10)
    u_password = models.CharField(max_length=255)
    u_ticket = models.CharField(max_length=30, null=True)

    class Meta:
        db_table = 'day51_user'

(2)urls.py 配置相關(guān)路由

from django.conf.urls import url
from uauth import views
urlpatterns = [
    url(r'^regist/', views.regist),
    url(r'^login/', views.login),
    url(r'^logout', views.logout)
]

(3)views.py 書寫regist方法

導(dǎo)入相關(guān)的包,在regist,login,logout都會使用到

import random
import  time
from django.contrib import auth
from django.contrib.auth.hashers import make_password,check_password
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from django.core.urlresolvers import reverse
# Create your views here.
from uauth.models import Users

如果用戶請求regist方法,則直接跳轉(zhuǎn)到相關(guān)的html頁面。
如果用戶在html頁面點(diǎn)擊了post按鈕,對密碼進(jìn)行加密后,將數(shù)據(jù)提交到數(shù)據(jù)庫,并返回登錄login頁面。

獲得post提交的表單文字,使用request.POST.get(' ')

def regist(request):
    if request.method == 'GET':
        return render(request, 'day6_regist.html')
    if request.method == 'POST':
        # 注冊
        name = request.POST.get('name')
        password = request.POST.get('password')
        # 對密碼進(jìn)行加密
        password = make_password(password)
        Users.objects.create(u_name=name, u_password=password)
        return HttpResponseRedirect('/uauth/login/')

編寫regist的提交表單, method方法選擇'POST'
文件目錄在templates下[圖片上傳中...(image.png-cc7763-1526105439415-0)]
{%csrf_token%}是針對提交的時(shí)候csrf跨域錯(cuò)誤

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注冊頁面</title>
</head>
<body>
<form action="" method="POST">
    {% csrf_token %}
    注冊姓名:<input type="text" name="name">
    注冊密碼:<input type="password" name="password">
    <input type="submit" value="提交">
</form>
</body>
</html>

2.登錄login

(1)配置路由urls.py, 與注冊的時(shí)候一樣的操作
(2)配置views.py, 編寫login方法
如果是GET請求,則跳轉(zhuǎn)到登錄的html界面中

def login(request):
    if request.method == 'GET':
        return render(request, 'day6_login.html')

如果是POST請求,則將獲得的用戶密碼與數(shù)據(jù)庫的用戶密碼進(jìn)行比較。如果相同,就賦值一個(gè)ticker到瀏覽器上,將ticket存入數(shù)據(jù)庫中,這樣后續(xù)的瀏覽器操作只需判斷ticket是否正確就好,如果錯(cuò)誤,返回登錄界面

知識點(diǎn)
綁定cookie命令: set_cookie
查詢一個(gè)用戶是否存在:exists()

def login(request):
    if request.method == 'GET':
        return render(request, 'day6_login.html')

    if request.method == 'POST':
        # 如果登錄成功,綁定參數(shù)到cookie中,set_cookie
        name = request.POST.get('name')
        password = request.POST.get('password')
        # 查詢用戶是否在數(shù)據(jù)庫中
        if Users.objects.filter(u_name=name).exists():
            user = Users.objects.get(u_name=name)
            if check_password(password, user.u_password):
                # ticket = 'agdoajbfjad'
                ticket = ''
                for i in range(15):
                    s = 'abcdefghijklmnopqrstuvwxyz'
                    # 獲取隨機(jī)的字符串
                    ticket += random.choice(s)
                now_time = int(time.time())
                ticket = 'TK' + ticket + str(now_time)
                # 綁定令牌到cookie里面
                # response = HttpResponse()
                response = HttpResponseRedirect('/stu/index/')
                #max_age 存活時(shí)間(秒)
                response.set_cookie('ticket', ticket, max_age=10000)
                # 存在服務(wù)端
                user.u_ticket = ticket
                user.save() #保存
                return response
            else:
                # return HttpResponse('用戶密碼錯(cuò)誤')
                return render(request, 'day6_login.html', {'password': '用戶密碼錯(cuò)誤'})
        else:
            # return HttpResponse('用戶不存在')
            return render(request, 'day6_login.html', {'name': '用戶不存在'})

登錄相關(guān)的html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登錄頁面</title>
</head>
<body>
<form action="" method="POST">
    {% csrf_token %}
    登錄姓名:<input type="text" name="name">
    登錄密碼:<input type="password" name="password">
    <input type="submit" value="提交">
</form>
</body>
</html>

相關(guān)的數(shù)據(jù)庫

image.png

補(bǔ)充說明:如何在主頁中判斷ticket
知識點(diǎn):獲得瀏覽器cookie攜帶的ticket: request.COOKIES.get('ticket')
這只能判斷一個(gè)網(wǎng)頁需不需要進(jìn)行判斷驗(yàn)證,如果需要很多網(wǎng)頁進(jìn)行驗(yàn)證,這是需要采用中間件,這個(gè)稍候會涉及到

   def index(request):
    if request.method == 'GET':
        # 獲取所有學(xué)生信息
        ticket = request.COOKIES.get('ticket')
        if not ticket:
            return HttpResponseRedirect('/uauth/login/')
        if Users.objects.filter(u_ticket=ticket).exists():
            stuinfos = StudentInfo.objects.all()
            return render(request, 'index.html', {'stuinfos': stuinfos})
        else:
            return HttpResponseRedirect('/uauth/login/')

3.登出系統(tǒng)

實(shí)現(xiàn)登出目的,選擇刪除數(shù)據(jù)庫中的ticket:delete_cookie
登出過后,自動跳轉(zhuǎn)到登錄界面

def logout(request):
    if request.method == 'GET':
        # response = HttpResponse()
        response = HttpResponseRedirect('/uauth/login/')
        response.delete_cookie('ticket')
        return response

4.中間件middleware

應(yīng)用:在django中,中間件其實(shí)就是一個(gè)類,在請求到來和結(jié)束后,django會根據(jù)自己的規(guī)則在合適的時(shí)機(jī)執(zhí)行中間件中相應(yīng)的方法。

  • 中間件的5個(gè)方法:

process_request(self,request) :當(dāng)用戶發(fā)起請求的時(shí)候會依次經(jīng)過所有的的中間件,這個(gè)時(shí)候的請求是process_request :

process_view(self, request, callback, callback_args, callback_kwargs) :進(jìn)入views函數(shù), 執(zhí)行process_view

process_template_response(self,request,response) : 只有當(dāng)views函數(shù)中返回的對象中具有render方法,是就會直接process_template_responseprocess

process_exception(self, request, exception) : 當(dāng)views的函數(shù)中出現(xiàn)錯(cuò)誤時(shí),就會執(zhí)行process_exception方法

process_response(self, request, response)
:views函數(shù)處理后,在依次穿過中間件,這個(gè)時(shí)候是process_response,最后返回給請求者

  • 中間件的運(yùn)行流程


    QQ圖片20180512143410.png

5. 使用中間件完成登錄的驗(yàn)證

中間件return None 或什么都不返回的時(shí)候表示什么都不做,跳過這一個(gè)過程
配置中間件,實(shí)現(xiàn)登錄的驗(yàn)證
(1)配置settings.py
1) 在主工程文件下創(chuàng)建一個(gè)utils文件,
在utils里: a. 創(chuàng)建中間件文件(名字自己?。? b.創(chuàng)建一個(gè)工程文件__init__.py

image.png

2)settings.py配置
在MIDDILEWARE里添加相關(guān)的文件路徑
QQ圖片20180512150130.png

3) 配置相關(guān)的中間件文件

from django.http import HttpResponseRedirect
from django.utils.deprecation import MiddlewareMixin

from uauth.models import Users
from stu.models import Countaddstu


class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # 統(tǒng)一驗(yàn)證登錄
        # return none 或者 不寫return才會繼續(xù)往下執(zhí)行, 不需要執(zhí)行
        if request.path == '/uauth/login/' or request.path == '/uauth/regist/':
            return None
        ticket = request.COOKIES.get('ticket')
        if not ticket:
            return HttpResponseRedirect('/uauth/login/')

        users = Users.objects.filter(u_ticket=ticket)
        if not users:
            return HttpResponseRedirect('/uauth/login/')
# 將user賦值在request請求的user上,以后可以直接判斷user有沒有存在
# 備注,django自帶的有user值
        request.user = users[0]

6. 至此,自己建造的登錄驗(yàn)證系統(tǒng)已經(jīng)完成

二、 django自帶的登錄驗(yàn)證系統(tǒng)

自帶的登錄驗(yàn)證系統(tǒng)中不需要自己手動的設(shè)置ticket

1.settings.py文件中配置沒登錄的跳轉(zhuǎn)頁面

LOGIN_URL = '/uauth/dglogin'

2.urls.py中配置相關(guān)路由

from django.conf.urls import url
from uauth import views
urlpatterns = [
    url(r'dglogin/', views.dglogin),
    url(r'^dgregist/', views.dgregist),
    url(r'^dglogout/', views.dglogout)
]

3. views.py導(dǎo)入相關(guān)的庫文件

from django.contrib import auth
from django.contrib.auth.hashers import make_password, check_password
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render

4.views.py文件中書寫注冊dgregist方法

from django.contrib.auth.models import User
def dgregist(request):
    if request.method == 'GET':
        return render(request, 'day6_regist.html')
    if request.method == 'POST':
        name = request.POST.get('name')
        password = request.POST.get('password')
        User.objects.create_user(username=name, password=password)
        return HttpResponseRedirect('/uauth/dglogin/')

5. views.py文件中書寫注冊dglogin方法


def dglogin(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    if request.method == 'POST':
        name = request.POST.get('name')
        password = request.POST.get('password')
        # 驗(yàn)證用戶名和密碼,通過的話,返回User對象
        user = auth.authenticate(username=name, password=password)
        if user:
    
            auth.login(request, user)
            return HttpResponseRedirect('/stu/index/')
        else:
            return render(request, 'index.html')

6. 在app的urls.py中設(shè)置驗(yàn)證require

from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from stu import views
urlpatterns = [
    url(r'addstu/', login_required(views.addStu), name='add'),
    url(r'index/', login_required(views.index)),
]

7.登出dglogout

def dglogout(request):

    if request.method == 'GET':
        auth.logout(request)
        return HttpResponseRedirect('/uauth/dglogin')
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容