Django實戰(zhàn)之用戶認證(用戶登錄與注銷)
上一篇中,我們已經(jīng)打開了Django自帶的用戶認證模塊,并配置了數(shù)據(jù)庫連接,創(chuàng)建了相應(yīng)的表,本篇我們將在Django自帶的用戶認證的基礎(chǔ)上,實現(xiàn)自己個性化的用戶登錄和注銷模塊。
首先,我們自己定義一個用戶登錄表單(forms.py):
from django import forms from django.contrib.auth.models import User from bootstrap_toolkit.widgets import BootstrapDateInput, BootstrapTextInput, BootstrapUneditableInput class LoginForm(forms.Form): username = forms.CharField( required=True, label=u"用戶名", error_messages={'required': '請輸入用戶名'}, widget=forms.TextInput( attrs={ 'placeholder':u"用戶名", } ), ) password = forms.CharField( required=True, label=u"密碼", error_messages={'required': u'請輸入密碼'}, widget=forms.PasswordInput( attrs={ 'placeholder':u"密碼", } ), ) def clean(self): if not self.is_valid(): raise forms.ValidationError(u"用戶名和密碼為必填項") else: cleaned_data = super(LoginForm, self).clean()
我們定義的用戶登錄表單有兩個域username和password,這兩個域都為必填項。
接下來,我們定義用戶登錄視圖(views.py),在該視圖里實例化之前定義的用戶登錄表單
from django.shortcuts import render_to_response,render,get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth.models import User from django.contrib import auth from django.contrib import messages from django.template.context import RequestContext from django.forms.formsets import formset_factory from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from bootstrap_toolkit.widgets import BootstrapUneditableInput from django.contrib.auth.decorators import login_required from .forms import LoginForm def login(request): if request.method == 'GET': form = LoginForm() return render_to_response('login.html', RequestContext(request, {'form': form,})) else: form = LoginForm(request.POST) if form.is_valid(): username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None and user.is_active: auth.login(request, user) return render_to_response('index.html', RequestContext(request)) else: return render_to_response('login.html', RequestContext(request, {'form': form,'password_is_wrong':True})) else: return render_to_response('login.html', RequestContext(request, {'form': form,}))
該視圖實例化了之前定義的LoginForm,它的主要業(yè)務(wù)邏輯是:
1. 判斷必填項用戶名和密碼是否為空,如果為空,提示"用戶名和密碼為必填項”的錯誤信息
2. 判斷用戶名和密碼是否正確,如果錯誤,提示“用戶名或密碼錯誤"的錯誤信息
3. 登陸成功后,進入主頁(index.html)
其中,登錄頁面的模板(login.html)定義如下:
<!DOCTYPE html> {% load bootstrap_toolkit %} {% load url from future %} <html lang="en"> <head> <meta charset="utf-8"> <title>數(shù)據(jù)庫腳本發(fā)布系統(tǒng)</title> <meta name="description" content=""> <meta name="author" content="朱顯杰"> {% bootstrap_stylesheet_tag %} {% bootstrap_stylesheet_tag "responsive" %} <style type="text/css"> body { padding-top: 60px; } </style> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> {% bootstrap_javascript_tag %} {% block extra_head %}{% endblock %} </head> <body> {% if password_is_wrong %} <div class="alert alert-error"> <button type="button" class="close" data-dismiss="alert">×</button> <h4>錯誤!</h4>用戶名或密碼錯誤 </div> {% endif %} <div class="well"> <h1>數(shù)據(jù)庫腳本發(fā)布系統(tǒng)</h1> <p> </p> <form class="form-horizontal" action="" method="post"> {% csrf_token %} {{ form|as_bootstrap:"horizontal" }} <p class="form-actions"> <input type="submit" value="登錄" class="btn btn-primary"> <a href="/contactme/" rel="external nofollow" rel="external nofollow" ><input type="button" value="忘記密碼" class="btn btn-danger"></a> <a href="/contactme/" rel="external nofollow" rel="external nofollow" ><input type="button" value="新員工?" class="btn btn-success"></a> </p> </form> </div> </body> </html>
最后還需要在urls.py里添加:
(r'^accounts/login/$', 'dbrelease_app.views.login'),
最終的效果如下:
1)當在瀏覽器里輸入http://192.168.1.16:8000/accounts/login/,出現(xiàn)如下登陸界面:
2)當用戶名或密碼為空時,提示”用戶名和密碼為必填項",如下所示:
3)當用戶名或密碼錯誤時,提示“用戶名或密碼錯誤",如下所示:
4)如果用戶名和密碼都正確,進入主頁(index.html)。
既然有l(wèi)ogin,當然要有l(wèi)ogout,logout比較簡單,直接調(diào)用Django自帶用戶認證系統(tǒng)的logout,然后返回登錄界面,具體如下(views.py):
@login_required def logout(request): auth.logout(request) return HttpResponseRedirect("/accounts/login/")
上面@login_required表示只有用戶在登錄的情況下才能調(diào)用該視圖,否則將自動重定向至登錄頁面。
urls.py里添加:
(r'^accounts/logout/$', 'dbrelease_app.views.logout'),
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python?selenium中Excel數(shù)據(jù)維護指南
這篇文章主要給大家介紹了關(guān)于python?selenium中Excel數(shù)據(jù)維護的相關(guān)資料,文中通過實例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友可以參考下2022-03-03python實現(xiàn)定時任務(wù)的八種方式總結(jié)
在日常工作中,我們常常會用到需要周期性執(zhí)行的任務(wù),下面這篇文章主要給大家介紹了關(guān)于python實現(xiàn)定時任務(wù)的八種方式,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-01-01numpy 矩陣形狀調(diào)整:拉伸、變成一位數(shù)組的實例
這篇文章主要介紹了numpy 矩陣形狀調(diào)整:拉伸、變成一位數(shù)組的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06Python多線程與異步處理在HTTP請求中的應(yīng)用方式
這篇文章主要介紹了Python多線程與異步處理在HTTP請求中的應(yīng)用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06