最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

django的登錄注冊系統(tǒng)的示例代碼

 更新時間:2018年05月14日 10:58:47   作者:裴general  
這篇文章主要介紹了django的登錄注冊系統(tǒng)的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

摘要

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

一、自己寫登錄注冊登出

1.注冊regist

注冊采用的是form表單,提交到數(shù)據(jù)庫,在登錄的時候,查詢數(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頁面點擊了post按鈕,對密碼進行加密后,將數(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')
    # 對密碼進行加密
    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%}是針對提交的時候csrf跨域錯誤

<!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, 與注冊的時候一樣的操作

(2)配置views.py, 編寫login方法

如果是GET請求,則跳轉(zhuǎn)到登錄的html界面中

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

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

知識點

綁定cookie命令: set_cookie

查詢一個用戶是否存在: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'
          # 獲取隨機的字符串
          ticket += random.choice(s)
        now_time = int(time.time())
        ticket = 'TK' + ticket + str(now_time)
        # 綁定令牌到cookie里面
        # response = HttpResponse()
        response = HttpResponseRedirect('/stu/index/')
        #max_age 存活時間(秒)
        response.set_cookie('ticket', ticket, max_age=10000)
        # 存在服務(wù)端
        user.u_ticket = ticket
        user.save() #保存
        return response
      else:
        # return HttpResponse('用戶密碼錯誤')
        return render(request, 'day6_login.html', {'password': '用戶密碼錯誤'})
    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ù)庫

補充說明:如何在主頁中判斷ticket

知識點:獲得瀏覽器cookie攜帶的ticket: request.COOKIES.get('ticket')

這只能判斷一個網(wǎng)頁需不需要進行判斷驗證,如果需要很多網(wǎng)頁進行驗證,這是需要采用中間件,這個稍候會涉及到

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)

實現(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中,中間件其實就是一個類,在請求到來和結(jié)束后,django會根據(jù)自己的規(guī)則在合適的時機執(zhí)行中間件中相應(yīng)的方法。

中間件的5個方法:

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

process_view(self, request, callback, callback_args, callback_kwargs) :進入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)錯誤時,就會執(zhí)行process_exception方法

process_response(self, request, response)

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

中間件的運行流程

5. 使用中間件完成登錄的驗證

中間件return None 或什么都不返回的時候表示什么都不做,跳過這一個過程

配置中間件,實現(xiàn)登錄的驗證

(1)配置settings.py

1) 在主工程文件下創(chuàng)建一個utils文件,

在utils里: a. 創(chuàng)建中間件文件(名字自己?。?b.創(chuàng)建一個工程文件 __init__.py

2)settings.py配置

在MIDDILEWARE里添加相關(guān)的文件路徑

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)一驗證登錄
    # 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. 至此,自己建造的登錄驗證系統(tǒng)已經(jīng)完成

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

自帶的登錄驗證系統(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')
    # 驗證用戶名和密碼,通過的話,返回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è)置驗證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')

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 使用NumPy讀取MNIST數(shù)據(jù)的實現(xiàn)代碼示例

    使用NumPy讀取MNIST數(shù)據(jù)的實現(xiàn)代碼示例

    這篇文章主要介紹了使用NumPy讀取MNIST數(shù)據(jù)的實現(xiàn)代碼示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • Python?Generator生成器函數(shù)基本概念及高級用途技巧示例

    Python?Generator生成器函數(shù)基本概念及高級用途技巧示例

    這篇文章主要為大家介紹了Python?Generator生成器函數(shù)基本概念及高級用途技巧示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-12-12
  • 編寫自定義的Django模板加載器的簡單示例

    編寫自定義的Django模板加載器的簡單示例

    這篇文章主要介紹了編寫自定義的Django模板加載器的簡單示例,Django是各色人氣Python框架中最為著名的一個,需要的朋友可以參考下
    2015-07-07
  • 基于Python編寫個語法解析器

    基于Python編寫個語法解析器

    這篇文章主要為大家詳細介紹了如何基于Python編寫個語法解析器,文中的示例代碼講解詳細,具有一定的學(xué)習(xí)價值,感興趣的小伙伴可以了解一下
    2023-07-07
  • Python控制windows系統(tǒng)音量實現(xiàn)實例

    Python控制windows系統(tǒng)音量實現(xiàn)實例

    這篇文章主要介紹了Python控制windows系統(tǒng)音量實現(xiàn)實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧
    2023-01-01
  • Python 面試中 8 個必考問題

    Python 面試中 8 個必考問題

    這篇文章主要介紹了Python 面試中 8 個必考問題,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-11-11
  • Python 專題三 字符串的基礎(chǔ)知識

    Python 專題三 字符串的基礎(chǔ)知識

    在Python中最重要的數(shù)據(jù)類型包括字符串、列表、元組和字典等。本篇文章主要講述Python的字符串基礎(chǔ)知識。下面跟著小編一起來看下吧
    2017-03-03
  • python 模擬網(wǎng)站登錄——滑塊驗證碼的識別

    python 模擬網(wǎng)站登錄——滑塊驗證碼的識別

    這篇文章主要介紹了python 模擬網(wǎng)站登錄——滑塊驗證碼的識別,幫助大家更好的理解和學(xué)習(xí)使用python的爬蟲技術(shù),感興趣的朋友可以了解下
    2021-03-03
  • Python連接SQLServer2000的方法詳解

    Python連接SQLServer2000的方法詳解

    這篇文章主要介紹了Python連接SQLServer2000的方法,結(jié)合實例形式分析了Python實現(xiàn)數(shù)據(jù)庫連接過程中所遇到的常見問題與相關(guān)注意事項,需要的朋友可以參考下
    2017-04-04
  • Python入門教程(十二)Python列表

    Python入門教程(十二)Python列表

    這篇文章主要介紹了Python入門教程(十二)Python列表,Python是一門非常強大好用的語言,也有著易上手的特性,本文為入門教程,需要的朋友可以參考下
    2023-04-04

最新評論

康乐县| 吉林市| 五峰| 临洮县| 淳化县| 凤翔县| 林周县| 淮滨县| 晴隆县| 郑州市| 镇坪县| 瑞金市| 临夏县| 科技| 团风县| 城固县| 鄂温| 繁昌县| 岱山县| 临武县| 西和县| 中卫市| 康马县| 彰化市| 磐石市| 克东县| 巫山县| 蒲江县| 安丘市| 威海市| 屏南县| 肥城市| 黄骅市| 水富县| 巴青县| 鲁山县| 德化县| 繁昌县| 霍城县| 蓬莱市| 祁东县|