您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了Django如何實現(xiàn)用戶登錄與注冊系統(tǒng),內(nèi)容簡而易懂,希望大家可以學習一下,學習完之后肯定會有收獲的,下面讓小編帶大家一起來看看吧。
1.1.創(chuàng)建項目和app
django-admin startproject mysite_login python manage.py startapp login
1.2.設置時區(qū)和語言
Django默認使用美國時間和英語,在項目的settings文件中,如下所示:
LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True
我們把它改為亞洲/上海
時間和中文
LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ = False
1.3.啟動
運行測試一下工程,在本機的瀏覽器中訪問http://127.0.0.1:8000/
二、設計數(shù)據(jù)模型
2.1.數(shù)據(jù)庫模型設計
作為一個用戶登錄和注冊項目,需要保存的都是各種用戶的相關信息。很顯然,我們至少需要一張用戶表User,在用戶表里需要保存下面的信息:
進入login/models.py,代碼如下
# login/models.py from django.db import models class User(models.Model): '''用戶表''' gender = ( ('male','男'), ('female','女'), ) name = models.CharField(max_length=128,unique=True) password = models.CharField(max_length=256) email = models.EmailField(unique=True) sex = models.CharField(max_length=32,choices=gender,default='男') c_time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Meta: ordering = ['c_time'] verbose_name = '用戶' verbose_name_plural = '用戶'
各字段含義:
注意:這里的用戶名指的是網(wǎng)絡上注冊的用戶名,不要等同于現(xiàn)實中的真實姓名,所以采用了唯一機制。如果是現(xiàn)實中可以重復的人名,那肯定是不能設置unique的。
2.2.設置數(shù)據(jù)庫為Mysql
在settings.py修改
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django', #數(shù)據(jù)庫名字 'USER': 'root', #賬號 'PASSWORD': '123456', #密碼 'HOST': '127.0.0.1', #IP 'PORT': '3306', #端口 } }
init.py里面導入pymysql模塊
# login/init.py import pymysql pymysql.install_as_MySQLdb()
2.3.數(shù)據(jù)庫遷移
注冊app
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'login', ]
遷移到數(shù)據(jù)庫
python manage.py makemigrations python manage.py migrate
三、admin后臺
3.1.在admin中注冊模型
# login/admin.py from django.contrib import admin from . import models admin.site.register(models.User)
3.2.創(chuàng)建超級管理員
python manage.py createsuperuser
然后再增加幾個測試用戶
四、url路由和視圖
前面我們已經(jīng)創(chuàng)建好數(shù)據(jù)模型了,并且在admin后臺中添加了一些測試用戶。下面我們就要設計好站點的url路由、對應的處理視圖函數(shù)以及使用的前端模板了。
4.1.路由設計
初步設想需要下面的四個URL:
考慮到登錄系統(tǒng)屬于站點的一級功能,為了直觀和更易于接受,這里沒有采用二級路由的方式,而是在根路由下直接編寫路由條目,同樣也沒有使用反向解析名(name參數(shù))。
# mysite_login/urls.py from django.conf.urls import url from django.contrib import admin from login import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/', views.index), url(r'^login/', views.login), url(r'^register/', views.register), url(r'^logout/', views.logout), ]
4.2.架構初步視圖
路由寫好了,就進入login/views.py
文件編寫視圖的框架,代碼如下:
# login/views.py from django.shortcuts import render,redirect def index(request): pass return render(request,'login/index.html') def login(request): pass return render(request,'login/login.html') def register(request): pass return render(request,'login/register.html') def logout(request): pass return redirect('/index/')
我們先不著急完成視圖內(nèi)部的具體細節(jié),而是把框架先搭建起來。
4.3.創(chuàng)建HTML頁面文件
在項目根路徑的login目錄中創(chuàng)建一個templates目錄,再在templates目錄里創(chuàng)建一個login目錄
在login/templates/login
目錄中創(chuàng)建三個文件index.html
、login.html
以及register.html
,并寫入如下的代碼:
index.html
{#login/templates/login/index.html#} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首頁</title> </head> <body> <h2>首頁</h2> </body> </html>
login.html
{#login/templates/login/login.html#} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登錄</title> </head> <body> <h2>登錄頁面</h2> </body> </html>
register.html
{#login/templates/login/register.html#} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注冊</title> </head> <body> <h2>注冊頁面</h2> </body> </html>
五、前端頁面設計
5.1.原生HTML頁面
login.html
文件中的內(nèi)容,寫入下面的代碼:
{#login/templates/login/login.html#} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登錄</title> </head> <body> <div > <h2>歡迎登錄!</h2> <form action="/login/" method="post"> <p> <label for="id_username">用戶名:</label> <input type="text" id="id_username" name="username" placeholder="用戶名" autofocus required /> </p> <p> <label for="id_password">密碼:</label> <input type="password" id="id_password" placeholder="密碼" name="password" required > </p> <input type="submit" value="確定"> </form> </div> </body> </html>
可以看到如下圖的頁面:
5.2.引入Bootstrap
Bootstrap3.3.7下載地址
根目錄下新建一個static目錄,并將解壓后的bootstrap-3.3.7-dist
目錄,整體拷貝到static目錄中,如下圖所示:
由于Bootstrap依賴JQuery,所以我們需要提前下載并引入JQuery:
下載地址
在static目錄下,新建一個css和js目錄,作為以后的樣式文件和js文件的存放地,將我們的jquery文件拷貝到static/js
目錄下。
然后打開項目的settings文件,在最下面添加配置,用于指定靜態(tài)文件的搜索目錄:
STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ]
5.3.創(chuàng)建base.html模板
既然要將前端頁面做得像個樣子,那么就不能和前面一樣,每個頁面都各寫各的,單打獨斗。一個網(wǎng)站有自己的統(tǒng)一風格和公用部分,可以把這部分內(nèi)容集中到一個基礎模板base.html
中?,F(xiàn)在,在根目錄下的templates中新建一個base.html
文件用作站點的基礎模板。
在Bootstrap文檔中,為我們提供了一個非常簡單而又實用的基本模板,代碼如下:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3個meta標簽*必須*放在最前面,任何其他內(nèi)容都*必須*跟隨其后! --> <title>Bootstrap 101 Template</title> <!-- Bootstrap --> <link href="css/bootstrap.min.css" rel="external nofollow" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <h2>你好,世界!</h2> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/bootstrap.min.js"></script> </body> </html>
將它整體拷貝到base.html
文件中。
5.4.創(chuàng)建頁面導航條
Bootstrap提供了現(xiàn)成的導航條組件
<nav class="navbar navbar-default"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Brand</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li class="active"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Link <span class="sr-only">(current)</span></a></li> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Link</a></li> <li class="dropdown"> <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Action</a></li> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Another action</a></li> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Something else here</a></li> <li role="separator" class="divider"></li> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Separated link</a></li> <li role="separator" class="divider"></li> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >One more separated link</a></li> </ul> </li> </ul> <form class="navbar-form navbar-left"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> <ul class="nav navbar-nav navbar-right"> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Link</a></li> <li class="dropdown"> <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Action</a></li> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Another action</a></li> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Something else here</a></li> <li role="separator" class="divider"></li> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Separated link</a></li> </ul> </li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav>
其中有一些部分,比如搜索框是我們目前還不需要的,需要將多余的內(nèi)容裁剪掉。同時,有一些名稱和url地址等需要按我們的實際內(nèi)容修改。最終導航條的代碼如下:
<nav class="navbar navbar-default"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#my-nav" aria-expanded="false"> <span class="sr-only">切換導航條</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Mysite</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="my-nav"> <ul class="nav navbar-nav"> <li class="active"><a href="/index/" rel="external nofollow" rel="external nofollow" rel="external nofollow" >主頁</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="/login/" rel="external nofollow" rel="external nofollow" rel="external nofollow" >登錄</a></li> <li><a href="/register/" rel="external nofollow" rel="external nofollow" rel="external nofollow" >注冊</a></li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav>
5.5.使用Bootstrap靜態(tài)文件
{% static '相對路徑' %}
這個Django為我們提供的靜態(tài)文件加載方法,可以將頁面與靜態(tài)文件鏈接起來
最后,base.html
內(nèi)容如下:
{% load staticfiles %} <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3個meta標簽*必須*放在最前面,任何其他內(nèi)容都*必須*跟隨其后! --> <title>{% block title %}base{% endblock %}</title> <!-- Bootstrap --> <link href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}" rel="external nofollow" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script> <![endif]--> {% block css %}{% endblock %} </head> <body> <nav class="navbar navbar-default"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#my-nav" aria-expanded="false"> <span class="sr-only">切換導航條</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Mysite</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="my-nav"> <ul class="nav navbar-nav"> <li class="active"><a href="/index/" rel="external nofollow" rel="external nofollow" rel="external nofollow" >主頁</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="/login/" rel="external nofollow" rel="external nofollow" rel="external nofollow" >登錄</a></li> <li><a href="/register/" rel="external nofollow" rel="external nofollow" rel="external nofollow" >注冊</a></li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> {% block content %}{% endblock %} <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="{% static 'js/jquery-3.2.1.js' %}"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script> </body> </html>
簡要說明:
看下效果
5.6.設計登錄頁面
Bootstarp提供了一個基本的表單樣式,代碼如下:
<form> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email"> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password"> </div> <div class="form-group"> <label for="exampleInputFile">File input</label> <input type="file" id="exampleInputFile"> <p class="help-block">Example block-level help text here.</p> </div> <div class="checkbox"> <label> <input type="checkbox"> Check me out </label> </div> <button type="submit" class="btn btn-default">Submit</button> </form>
如下:
我們結合Bootstrap和前面自己寫的form表單,修改login/templates/login/login.html
成符合項目要求的樣子:
{% extends 'login/base.html' %} {% load staticfiles %} {% block title %}登錄{% endblock %} {% block css %} <link rel="stylesheet" href="{% static 'css/login.css' %}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > {% endblock %} {% block content %} <div class="container"> <div class="col-md-4 col-md-offset-4"> <form class='form-login' action="/login/" method="post"> <h3 class="text-center">歡迎登錄</h3> <div class="form-group"> <label for="id_username">用戶名:</label> <input type="text" name='username' class="form-control" id="id_username" placeholder="Username" autofocus required> </div> <div class="form-group"> <label for="id_password">密碼:</label> <input type="password" name='password' class="form-control" id="id_password" placeholder="Password" required> </div> <button type="reset" class="btn btn-default pull-left">重置</button> <button type="submit" class="btn btn-primary pull-right">提交</button> </form> </div> </div> <!-- /container --> {% endblock %}
說明:
在static/css
目錄中新建一個login.css
樣式文件,這里簡單地寫了點樣式,
body { background-color: #eee; } .form-login { max-width: 330px; padding: 15px; margin: 0 auto; } .form-login .form-control { position: relative; height: auto; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; padding: 10px; font-size: 16px; } .form-login .form-control:focus { z-index: 2; } .form-login input[type="text"] { margin-bottom: -1px; border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .form-login input[type="password"] { margin-bottom: 10px; border-top-left-radius: 0; border-top-right-radius: 0; }
最后效果
六、登錄視圖
6.1.登錄視圖
根據(jù)我們在路由中的設計,用戶通過login.html
中的表單填寫用戶名和密碼,并以POST的方式發(fā)送到服務器的/login/
地址。服務器通過login/views.py
中的login()
視圖函數(shù),接收并處理這一請求。
我們可以通過下面的方法接收和處理請求:
def login(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') return redirect('/index/') return render(request, 'login/login.html')
還需要在前端頁面的form表單內(nèi)添加一個{% csrf_token %}
標簽:
<form class='form-login' action="/login/" method="post"> {% csrf_token %} <h3 class="text-center">歡迎登錄</h3> <div class="form-group"> ...... </form>
進入登錄頁面,輸入用戶名,密碼然后跳轉到index頁面。
6.2.數(shù)據(jù)驗證
通過唯一的用戶名,使用Django的ORM去數(shù)據(jù)庫中查詢用戶數(shù)據(jù),如果有匹配項,則進行密碼對比,如果沒有匹配項,說明用戶名不存在。如果密碼對比錯誤,說明密碼不正確。
def login(request): if request.method == "POST": username = request.POST.get('username', None) password = request.POST.get('password', None) if username and password: # 確保用戶名和密碼都不為空 username = username.strip() # 用戶名字符合法性驗證 # 密碼長度驗證 # 更多的其它驗證..... try: user = models.User.objects.get(name=username) except: return render(request, 'login/login.html') if user.password == password: return redirect('/index/') return render(request, 'login/login.html')
6.3.添加提示信息
上面的代碼還缺少很重要的一部分內(nèi)容,提示信息!無論是登錄成功還是失敗,用戶都沒有得到任何提示信息,這顯然是不行的。
修改一下login視圖:
def login(request): if request.method == "POST": username = request.POST.get('username', None) password = request.POST.get('password', None) message = "所有字段都必須填寫!" if username and password: # 確保用戶名和密碼都不為空 username = username.strip() # 用戶名字符合法性驗證 # 密碼長度驗證 # 更多的其它驗證..... try: user = models.User.objects.get(name=username) if user.password == password: return redirect('/index/') else: message = "密碼不正確!" except: message = "用戶名不存在!" return render(request, 'login/login.html', {"message": message}) return render(request, 'login/login.html')
增加了message變量,用于保存提示信息。當有錯誤信息的時候,將錯誤信息打包成一個字典,然后作為第三個參數(shù)提供給render()方法。這個數(shù)據(jù)字典在渲染模板的時候會傳遞到模板里供你調用。
為了在前端頁面顯示信息,還需要對login.html
進行修改:
{% extends 'login/base.html' %} {% load staticfiles %} {% block title %}登錄{% endblock %} {% block css %} <link rel="stylesheet" href="{% static 'css/login.css' %}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > {% endblock %} {% block content %} <div class="container"> <div class="col-md-4 col-md-offset-4"> <form class='form-login' action="/login/" method="post"> {% if message %} <div class="alert alert-warning">{{ message }}</div> {% endif %} {% csrf_token %} <h3 class="text-center">歡迎登錄</h3> <div class="form-group"> <label for="id_username">用戶名:</label> <input type="text" name='username' class="form-control" id="id_username" placeholder="Username" autofocus required> </div> <div class="form-group"> <label for="id_password">密碼:</label> <input type="password" name='password' class="form-control" id="id_password" placeholder="Password" required> </div> <button type="reset" class="btn btn-default pull-left">重置</button> <button type="submit" class="btn btn-primary pull-right">提交</button> </form> </div> </div> <!-- /container --> {% endblock %}
把index.html
主頁模板也修改一下,刪除原有內(nèi)容,添加下面的代碼:
{#login/templates/login/index.html#} {% extends 'login/base.html' %} {% block title %}主頁{% endblock %} {% block content %} <h2>歡迎回來!</h2> {% endblock %}
七、Django表單
Django的表單給我們提供了下面三個主要功能:
7.1.創(chuàng)建表單模型
from django import forms class UserForm(forms.Form): username = forms.CharField(label="用戶名", max_length=128) password = forms.CharField(label="密碼", max_length=256, widget=forms.PasswordInput)
說明:
7.2.修改視圖
使用了Django的表單后,就要在視圖中進行相應的修改:
# login/views.py from django.shortcuts import render,redirect from . import models from .forms import UserForm def index(request): pass return render(request,'login/index.html') def login(request): if request.method == "POST": login_form = UserForm(request.POST) message = "請檢查填寫的內(nèi)容!" if login_form.is_valid(): username = login_form.cleaned_data['username'] password = login_form.cleaned_data['password'] try: user = models.User.objects.get(name=username) if user.password == password: return redirect('/index/') else: message = "密碼不正確!" except: message = "用戶不存在!" return render(request, 'login/login.html', locals()) login_form = UserForm() return render(request, 'login/login.html', locals())
說明:
另外,這里使用了一個小技巧,Python內(nèi)置了一個locals()函數(shù),它返回當前所有的本地變量字典,我們可以偷懶的將這作為render函數(shù)的數(shù)據(jù)字典參數(shù)值,就不用費勁去構造一個形如{'message':message, 'login_form':login_form}
的字典了。這樣做的好處當然是大大方便了我們,但是同時也可能往模板傳入了一些多余的變量數(shù)據(jù),造成數(shù)據(jù)冗余降低效率。
7.3.修改login界面
Django的表單很重要的一個功能就是自動生成HTML的form表單內(nèi)容?,F(xiàn)在,我們需要修改一下原來的login.html
文件:
{% extends 'base.html' %} {% load staticfiles %} {% block title %}登錄{% endblock %} {% block css %}<link href="{% static 'css/login.css' %}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="stylesheet"/>{% endblock %} {% block content %} <div class="container"> <div class="col-md-4 col-md-offset-4"> <form class='form-login' action="/login/" method="post"> {% if message %} <div class="alert alert-warning">{{ message }}</div> {% endif %} {% csrf_token %} <h3 class="text-center">歡迎登錄</h3> {{ login_form }} <button type="reset" class="btn btn-default pull-left">重置</button> <button type="submit" class="btn btn-primary pull-right">提交</button> </form> </div> </div> <!-- /container --> {% endblock %}
瀏覽器生成的HTML源碼
重新啟動服務器,刷新頁面,如下圖所示:
7.4.手動渲染表單
直接{{ login_form }}
雖然好,啥都不用操心,但是界面真的很丑,往往并不是你想要的,如果你要使用CSS和JS,比如你要引入Bootstarps框架,這些都需要對表單內(nèi)的input元素進行額外控制,那怎么辦呢?手動渲染字段就可以了。
可以通過{{ login_form.name_of_field }}
獲取每一個字段,然后分別渲染,如下例所示:
<div class="form-group"> {{ login_form.username.label_tag }} {{ login_form.username}} </div> <div class="form-group"> {{ login_form.password.label_tag }} {{ login_form.password }} </div>
然后,在form類里添加attr屬性即可,如下所示修改login/forms.py
from django import forms class UserForm(forms.Form): username = forms.CharField(label="用戶名", max_length=128, widget=forms.TextInput(attrs={'class': 'form-control'})) password = forms.CharField(label="密碼", max_length=256, widget=forms.PasswordInput(attrs={'class': 'form-control'}))
再次刷新頁面,就顯示正常了!
八、圖片驗證碼
為了防止機器人頻繁登錄網(wǎng)站或者破壞分子惡意登錄,很多用戶登錄和注冊系統(tǒng)都提供了圖形驗證碼功能。
驗證碼(CAPTCHA)是“Completely Automated Public Turing test to tell Computers and Humans Apart”(全自動區(qū)分計算機和人類的圖靈測試)的縮寫,是一種區(qū)分用戶是計算機還是人的公共全自動程序。可以防止惡意破解密碼、刷票、論壇灌水,有效防止某個黑客對某一個特定注冊用戶用特定程序暴力破解方式進行不斷的登陸嘗試。
圖形驗證碼的歷史比較悠久,到現(xiàn)在已經(jīng)有點英雄末路的味道了。因為機器學習、圖像識別的存在,機器人已經(jīng)可以比較正確的識別圖像內(nèi)的字符了。但不管怎么說,作為一種防御手段,至少還是可以抵擋一些低級入門的攻擊手段,抬高了攻擊者的門檻。
在Django中實現(xiàn)圖片驗證碼功能非常簡單,有現(xiàn)成的第三方庫可以使用,我們不必自己開發(fā)(也要能開發(fā)得出來,囧)。這個庫叫做django-simple-captcha
。
8.1.安裝captcha
直接安裝:pip install django-simple-captcha
Django自動幫我們安裝了相關的依賴庫six
、olefile
和Pillow
,其中的Pillow是大名鼎鼎的繪圖模塊。
注冊captcha
在settings中,將‘captcha'注冊到app列表里:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'login', 'captcha', ]
captcha需要在數(shù)據(jù)庫中建立自己的數(shù)據(jù)表,所以需要執(zhí)行migrate命令生成數(shù)據(jù)表:
python manage.py migrate
8.2.添加url路由
根目錄下的urls.py文件中增加captcha對應的網(wǎng)址:
from django.conf.urls import url from django.conf.urls import include from django.contrib import admin from login import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/', views.index), url(r'^login/', views.login), url(r'^register/', views.register), url(r'^logout/', views.logout), url(r'^captcha', include('captcha.urls')) # 增加這一行 ]
8.3.修改forms.py
如果上面都OK了,就可以直接在我們的forms.py文件中添加CaptchaField了。
from django import forms from captcha.fields import CaptchaField class UserForm(forms.Form): username = forms.CharField(label="用戶名", max_length=128, widget=forms.TextInput(attrs={'class': 'form-control'})) password = forms.CharField(label="密碼", max_length=256, widget=forms.PasswordInput(attrs={'class': 'form-control'})) captcha = CaptchaField(label='驗證碼')
需要提前導入from captcha.fields import CaptchaField
,然后就像寫普通的form字段一樣添加一個captcha字段就可以了!
8.4.修改login.html
由于我們前面是手動生成的form表單,所以還要修改一下,添加captcha的相關內(nèi)容,如下所示:
{% extends 'login/base.html' %} {% load staticfiles %} {% block title %}登錄{% endblock %} {% block css %} <link rel="stylesheet" href="{% static 'css/login.css' %}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > {% endblock %} {% block content %} <div class="container"> <div class="col-md-4 col-md-offset-4"> <form class='form-login' action="/login/" method="post"> {% if message %} <div class="alert alert-warning">{{ message }}</div> {% endif %} {% csrf_token %} <h3 class="text-center">歡迎登錄</h3> <div class="form-group"> {{ login_form.username.label_tag }} {{ login_form.username}} </div> <div class="form-group"> {{ login_form.password.label_tag }} {{ login_form.password }} </div> <div class="form-group"> {{ login_form.captcha.errors }} {{ login_form.captcha.label_tag }} {{ login_form.captcha }} </div> <button type="reset" class="btn btn-default pull-left">重置</button> <button type="submit" class="btn btn-primary pull-right">提交</button> </form> </div> </div> <!-- /container --> {% endblock %}
這里額外增加了一條{{ login_form.captcha.errors }}
用于明確指示用戶,你的驗證碼不正確
查看效果:
其中驗證圖形碼是否正確的工作都是在后臺自動完成的,只需要使用is_valid()
這個forms內(nèi)置的驗證方法就一起進行了,完全不需要在視圖函數(shù)中添加任何的驗證代碼,非常方便快捷!
九、session會話
因為因特網(wǎng)HTTP協(xié)議的特性,每一次來自于用戶瀏覽器的請求(request)都是無狀態(tài)的、獨立的。通俗地說,就是無法保存用戶狀態(tài),后臺服務器根本就不知道當前請求和以前及以后請求是否來自同一用戶。對于靜態(tài)網(wǎng)站,這可能不是個問題,而對于動態(tài)網(wǎng)站,尤其是京東、天貓、銀行等購物或金融網(wǎng)站,無法識別用戶并保持用戶狀態(tài)是致命的,根本就無法提供服務。你可以嘗試將瀏覽器的cookie功能關閉,你會發(fā)現(xiàn)將無法在京東登錄和購物。
為了實現(xiàn)連接狀態(tài)的保持功能,網(wǎng)站會通過用戶的瀏覽器在用戶機器內(nèi)被限定的硬盤位置中寫入一些數(shù)據(jù),也就是所謂的Cookie。通過Cookie可以保存一些諸如用戶名、瀏覽記錄、表單記錄、登錄和注銷等各種數(shù)據(jù)。但是這種方式非常不安全,因為Cookie保存在用戶的機器上,如果Cookie被偽造、篡改或刪除,就會造成極大的安全威脅,因此,現(xiàn)代網(wǎng)站設計通常將Cookie用來保存一些不重要的內(nèi)容,實際的用戶數(shù)據(jù)和狀態(tài)還是以Session會話的方式保存在服務器端。
Session依賴Cookie!但與Cookie不同的地方在于Session將所有的數(shù)據(jù)都放在服務器端,用戶瀏覽器的Cookie中只會保存一個非明文的識別信息,比如哈希值。
Django提供了一個通用的Session框架,并且可以使用多種session數(shù)據(jù)的保存方式:
通常情況,沒有特別需求的話,請使用保存在數(shù)據(jù)庫內(nèi)的方式,盡量不要保存到Cookie內(nèi)。
Django的session框架默認啟用,并已經(jīng)注冊在app設置內(nèi),如果真的沒有啟用,那么參考下面的內(nèi)容添加有說明的那兩行,再執(zhí)行migrate命令創(chuàng)建數(shù)據(jù)表,就可以使用session了。
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', # 這一行 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # 這一行 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
當session啟用后,傳遞給視圖request參數(shù)的HttpRequest對象將包含一個session屬性,就像一個字典對象一樣。你可以在Django的任何地方讀寫request.session
屬性,或者多次編輯使用它。
下面是session使用參考:
class backends.base.SessionBase # 這是所有會話對象的基類,包含標準的字典方法: __getitem__(key) Example: fav_color = request.session['fav_color'] __setitem__(key, value) Example: request.session['fav_color'] = 'blue' __delitem__(key) Example: del request.session['fav_color'] # 如果不存在會拋出異常 __contains__(key) Example: 'fav_color' in request.session get(key, default=None) Example: fav_color = request.session.get('fav_color', 'red') pop(key, default=__not_given) Example: fav_color = request.session.pop('fav_color', 'blue')
# 類似字典數(shù)據(jù)類型的內(nèi)置方法 keys() items() setdefault() clear() # 它還有下面的方法: flush() # 刪除當前的會話數(shù)據(jù)和會話cookie。經(jīng)常用在用戶退出后,刪除會話。 set_test_cookie() # 設置一個測試cookie,用于探測用戶瀏覽器是否支持cookies。由于cookie的工作機制,你只有在下次用戶請求的時候才可以測試。 test_cookie_worked() # 返回True或者False,取決于用戶的瀏覽器是否接受測試cookie。你必須在之前先調用set_test_cookie()方法。 delete_test_cookie() # 刪除測試cookie。 set_expiry(value) # 設置cookie的有效期??梢詡鬟f不同類型的參數(shù)值: • 如果值是一個整數(shù),session將在對應的秒數(shù)后失效。例如request.session.set_expiry(300) 將在300秒后失效. • 如果值是一個datetime或者timedelta對象, 會話將在指定的日期失效 • 如果為0,在用戶關閉瀏覽器后失效 • 如果為None,則將使用全局會話失效策略 失效時間從上一次會話被修改的時刻開始計時。 get_expiry_age() # 返回多少秒后失效的秒數(shù)。對于沒有自定義失效時間的會話,這等同于SESSION_COOKIE_AGE. # 這個方法接受2個可選的關鍵字參數(shù) • modification:會話的最后修改時間(datetime對象)。默認是當前時間。 •expiry: 會話失效信息,可以是datetime對象,也可以是int或None get_expiry_date() # 和上面的方法類似,只是返回的是日期 get_expire_at_browser_close() # 返回True或False,根據(jù)用戶會話是否是瀏覽器關閉后就結束。 clear_expired() # 刪除已經(jīng)失效的會話數(shù)據(jù)。 cycle_key() # 創(chuàng)建一個新的會話秘鑰用于保持當前的會話數(shù)據(jù)。django.contrib.auth.login() 會調用這個方法。
9.1.使用session
首先,修改login/views.py
中的login()視圖函數(shù):
def login(request): if request.session.get('is_login',None): return redirect('/index') if request.method == "POST": login_form = UserForm(request.POST) message = "請檢查填寫的內(nèi)容!" if login_form.is_valid(): username = login_form.cleaned_data['username'] password = login_form.cleaned_data['password'] try: user = models.User.objects.get(name=username) if user.password == password: request.session['is_login'] = True request.session['user_id'] = user.id request.session['user_name'] = user.name return redirect('/index/') else: message = "密碼不正確!" except: message = "用戶不存在!" return render(request, 'login/login.html', locals()) login_form = UserForm() return render(request, 'login/login.html', locals())
通過下面的if語句,我們不允許重復登錄:
if request.session.get('is_login',None): return redirect("/index/")
通過下面的語句,我們往session字典內(nèi)寫入用戶狀態(tài)和數(shù)據(jù):
request.session['is_login'] = True request.session['user_id'] = user.id request.session['user_name'] = user.name
你完全可以往里面寫任何數(shù)據(jù),不僅僅限于用戶相關!
既然有了session記錄用戶登錄狀態(tài),那么就可以完善我們的登出視圖函數(shù)了:
def logout(request): if not request.session.get('is_login', None): # 如果本來就未登錄,也就沒有登出一說 return redirect("/index/") request.session.flush() # 或者使用下面的方法 # del request.session['is_login'] # del request.session['user_id'] # del request.session['user_name'] return redirect("/index/")
flush()方法是比較安全的一種做法,而且一次性將session中的所有內(nèi)容全部清空,確保不留后患。但也有不好的地方,那就是如果你在session中夾帶了一點‘私貨',會被一并刪除,這一點一定要注意。
9.2.完善頁面
有了用戶狀態(tài),就可以根據(jù)用戶登錄與否,展示不同的頁面,比如導航條內(nèi)容:
首先,修改base.html
文件:
<div class="collapse navbar-collapse" id="my-nav"> <ul class="nav navbar-nav"> <li class="active"><a href="/index/" rel="external nofollow" rel="external nofollow" rel="external nofollow" >主頁</a></li> </ul> <ul class="nav navbar-nav navbar-right"> {% if request.session.is_login %} <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >當前在線:{{ request.session.user_name }}</a></li> <li><a href="/logout/" rel="external nofollow" >登出</a></li> {% else %} <li><a href="/login/" rel="external nofollow" rel="external nofollow" rel="external nofollow" >登錄</a></li> <li><a href="/register/" rel="external nofollow" rel="external nofollow" rel="external nofollow" >注冊</a></li> {% endif %} </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid -->
通過if判斷,當?shù)卿洉r,顯示當前用戶名和登出按鈕。未登錄時,顯示登錄和注冊按鈕。
注意其中的模板語言,{{ request }}
這個變量會被默認傳入模板中,可以通過圓點的調用方式,獲取它內(nèi)部的{{ request.session }}
,再進一步的獲取session中的內(nèi)容。其實{{ request }}
中的數(shù)據(jù)遠不止此,例如{{ request.path }}
就可以獲取先前的url地址。
再修改一下index.html
頁面,根據(jù)登錄與否的不同,顯示不同的內(nèi)容:
{% extends 'base.html' %} {% block title %}主頁{% endblock %} {% block content %} {% if request.session.is_login %} <h2>你好,{{ request.session.user_name }}!歡迎回來!</h2> {% else %} <h2>你尚未登錄,只能訪問公開內(nèi)容!</h2> {% endif %} {% endblock %}
看下效果:
十、注冊視圖
10.1.創(chuàng)建forms
在/login/forms.py
中添加一個新的表單類:
class RegisterForm(forms.Form): gender = ( ('male', "男"), ('female', "女"), ) username = forms.CharField(label="用戶名", max_length=128, widget=forms.TextInput(attrs={'class': 'form-control'})) password1 = forms.CharField(label="密碼", max_length=256, widget=forms.PasswordInput(attrs={'class': 'form-control'})) password2 = forms.CharField(label="確認密碼", max_length=256, widget=forms.PasswordInput(attrs={'class': 'form-control'})) email = forms.EmailField(label="郵箱地址", widget=forms.EmailInput(attrs={'class': 'form-control'})) sex = forms.ChoiceField(label='性別', choices=gender) captcha = CaptchaField(label='驗證碼')
說明:
10.2.完善register.html
同樣地,類似login.html文件,我們在register.html中編寫forms相關條目:
{% extends 'login/base.html' %} {% block title %}注冊{% endblock %} {% block content %} <div class="container"> <div class="col-md-4 col-md-offset-4"> <form class='form-register' action="/register/" method="post"> {% if message %} <div class="alert alert-warning">{{ message }}</div> {% endif %} {% csrf_token %} <h3 class="text-center">歡迎注冊</h3> <div class="form-group"> {{ register_form.username.label_tag }} {{ register_form.username}} </div> <div class="form-group"> {{ register_form.password1.label_tag }} {{ register_form.password1 }} </div> <div class="form-group"> {{ register_form.password2.label_tag }} {{ register_form.password2 }} </div> <div class="form-group"> {{ register_form.email.label_tag }} {{ register_form.email }} </div> <div class="form-group"> {{ register_form.sex.label_tag }} {{ register_form.sex }} </div> <div class="form-group"> {{ register_form.captcha.errors }} {{ register_form.captcha.label_tag }} {{ register_form.captcha }} </div> <button type="reset" class="btn btn-default pull-left">重置</button> <button type="submit" class="btn btn-primary pull-right">提交</button> </form> </div> </div> <!-- /container --> {% endblock %}
10.3.注冊視圖
進入/login/views.py
文件,現(xiàn)在來完善我們的register()
視圖:
def register(request): if request.session.get('is_login', None): # 登錄狀態(tài)不允許注冊。你可以修改這條原則! return redirect("/index/") if request.method == "POST": register_form = RegisterForm(request.POST) message = "請檢查填寫的內(nèi)容!" if register_form.is_valid(): # 獲取數(shù)據(jù) username = register_form.cleaned_data['username'] password1 = register_form.cleaned_data['password1'] password2 = register_form.cleaned_data['password2'] email = register_form.cleaned_data['email'] sex = register_form.cleaned_data['sex'] if password1 != password2: # 判斷兩次密碼是否相同 message = "兩次輸入的密碼不同!" return render(request, 'login/register.html', locals()) else: same_name_user = models.User.objects.filter(name=username) if same_name_user: # 用戶名唯一 message = '用戶已經(jīng)存在,請重新選擇用戶名!' return render(request, 'login/register.html', locals()) same_email_user = models.User.objects.filter(email=email) if same_email_user: # 郵箱地址唯一 message = '該郵箱地址已被注冊,請使用別的郵箱!' return render(request, 'login/register.html', locals()) # 當一切都OK的情況下,創(chuàng)建新用戶 new_user = models.User.objects.create() new_user.name = username new_user.password = password1 new_user.email = email new_user.sex = sex new_user.save() return redirect('/login/') # 自動跳轉到登錄頁面 register_form = RegisterForm() return render(request, 'login/register.html', locals())
從大體邏輯上,也是先實例化一個RegisterForm的對象,然后使用is_valide()
驗證數(shù)據(jù),再從cleaned_data
中獲取數(shù)據(jù)。
重點在于注冊邏輯,首先兩次輸入的密碼必須相同,其次不能存在相同用戶名和郵箱,最后如果條件都滿足,利用ORM的API,創(chuàng)建一個用戶實例,然后保存到數(shù)據(jù)庫內(nèi)。
看一下注冊的頁面:
注冊成功在admin后臺可以看到注冊的用戶
10.4.密碼加密
用戶注冊的密碼應該加密才對
對于如何加密密碼,有很多不同的途徑,其安全程度也高低不等。這里我們使用Python內(nèi)置的hashlib庫,使用哈希值的方式加密密碼,可能安全等級不夠高,但足夠簡單,方便使用,不是么?
首先在login/views.py
中編寫一個hash函數(shù):
import hashlib def hash_code(s, salt='mysite'):# 加點鹽 h = hashlib.sha256() s += salt h.update(s.encode()) # update方法只接收bytes類型 return h.hexdigest()
然后,我們還要對login()和register()視圖進行一下修改:
#login.html if user.password == hash_code(password): # 哈希值和數(shù)據(jù)庫內(nèi)的值進行比對 #register.html new_user.password = hash_code(password1) # 使用加密密碼
# login/views.py from django.shortcuts import render,redirect from . import models from .forms import UserForm,RegisterForm import hashlib def index(request): pass return render(request,'login/index.html') def login(request): if request.session.get('is_login', None): return redirect("/index/") if request.method == "POST": login_form = UserForm(request.POST) message = "請檢查填寫的內(nèi)容!" if login_form.is_valid(): username = login_form.cleaned_data['username'] password = login_form.cleaned_data['password'] try: user = models.User.objects.get(name=username) if user.password == hash_code(password): # 哈希值和數(shù)據(jù)庫內(nèi)的值進行比對 request.session['is_login'] = True request.session['user_id'] = user.id request.session['user_name'] = user.name return redirect('/index/') else: message = "密碼不正確!" except: message = "用戶不存在!" return render(request, 'login/login.html', locals()) login_form = UserForm() return render(request, 'login/login.html', locals()) def register(request): if request.session.get('is_login', None): # 登錄狀態(tài)不允許注冊。你可以修改這條原則! return redirect("/index/") if request.method == "POST": register_form = RegisterForm(request.POST) message = "請檢查填寫的內(nèi)容!" if register_form.is_valid(): # 獲取數(shù)據(jù) username = register_form.cleaned_data['username'] password1 = register_form.cleaned_data['password1'] password2 = register_form.cleaned_data['password2'] email = register_form.cleaned_data['email'] sex = register_form.cleaned_data['sex'] if password1 != password2: # 判斷兩次密碼是否相同 message = "兩次輸入的密碼不同!" return render(request, 'login/register.html', locals()) else: same_name_user = models.User.objects.filter(name=username) if same_name_user: # 用戶名唯一 message = '用戶已經(jīng)存在,請重新選擇用戶名!' return render(request, 'login/register.html', locals()) same_email_user = models.User.objects.filter(email=email) if same_email_user: # 郵箱地址唯一 message = '該郵箱地址已被注冊,請使用別的郵箱!' return render(request, 'login/register.html', locals()) # 當一切都OK的情況下,創(chuàng)建新用戶 new_user = models.User.objects.create() new_user.name = username new_user.password = hash_code(password1) # 使用加密密碼 new_user.email = email new_user.sex = sex new_user.save() return redirect('/login/') # 自動跳轉到登錄頁面 register_form = RegisterForm() return render(request, 'login/register.html', locals()) def logout(request): if not request.session.get('is_login',None): return redirect('/index/') request.session.flush() return redirect('/index/') def hash_code(s, salt='mysite_login'): h = hashlib.sha256() s += salt h.update(s.encode()) # update方法只接收bytes類型 return h.hexdigest()
重啟服務器,進入注冊頁面,新建一個用戶,然后進入admin后臺,查看用戶的密碼情況:
再使用該用戶登錄一下,大功告成!
可以看到密碼長度根據(jù)你哈希算法的不同,已經(jīng)變得很長了,所以前面model中設置password字段時,不要想當然的將max_length
設置為16這么小的數(shù)字。
以上就是關于Django如何實現(xiàn)用戶登錄與注冊系統(tǒng)的內(nèi)容,如果你們有學習到知識或者技能,可以把它分享出去讓更多的人看到。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。