欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Django實(shí)戰(zhàn)之用戶認(rèn)證(用戶登錄與注銷)

 更新時(shí)間:2018年07月16日 10:44:38   作者:Zhu_Julian  
這篇文章主要介紹了Django實(shí)戰(zhàn)之用戶認(rèn)證(用戶登錄與注銷),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

上一篇中,我們已經(jīng)打開了Django自帶的用戶認(rèn)證模塊,并配置了數(shù)據(jù)庫(kù)連接,創(chuàng)建了相應(yīng)的表,本篇我們將在Django自帶的用戶認(rèn)證的基礎(chǔ)上,實(shí)現(xiàn)自己個(gè)性化的用戶登錄和注銷模塊。

首先,我們自己定義一個(gè)用戶登錄表單(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': '請(qǐng)輸入用戶名'},
    widget=forms.TextInput(
      attrs={
        'placeholder':u"用戶名",
      }
    ),
  )  
  password = forms.CharField(
    required=True,
    label=u"密碼",
    error_messages={'required': u'請(qǐng)輸入密碼'},
    widget=forms.PasswordInput(
      attrs={
        'placeholder':u"密碼",
      }
    ),
  )  
  def clean(self):
    if not self.is_valid():
      raise forms.ValidationError(u"用戶名和密碼為必填項(xiàng)")
    else:
      cleaned_data = super(LoginForm, self).clean()

我們定義的用戶登錄表單有兩個(gè)域username和password,這兩個(gè)域都為必填項(xiàng)。

接下來,我們定義用戶登錄視圖(views.py),在該視圖里實(shí)例化之前定義的用戶登錄表單

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,}))

該視圖實(shí)例化了之前定義的LoginForm,它的主要業(yè)務(wù)邏輯是:

1. 判斷必填項(xiàng)用戶名和密碼是否為空,如果為空,提示"用戶名和密碼為必填項(xiàng)”的錯(cuò)誤信息

2. 判斷用戶名和密碼是否正確,如果錯(cuò)誤,提示“用戶名或密碼錯(cuò)誤"的錯(cuò)誤信息

3. 登陸成功后,進(jìn)入主頁(index.html)

其中,登錄頁面的模板(login.html)定義如下:

<!DOCTYPE html>
{% load bootstrap_toolkit %}
{% load url from future %}
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>數(shù)據(jù)庫(kù)腳本發(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>錯(cuò)誤!</h4>用戶名或密碼錯(cuò)誤
    </div>
  {% endif %}  
  <div class="well">
    <h1>數(shù)據(jù)庫(kù)腳本發(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)當(dāng)在瀏覽器里輸入http://192.168.1.16:8000/accounts/login/,出現(xiàn)如下登陸界面:


2)當(dāng)用戶名或密碼為空時(shí),提示”用戶名和密碼為必填項(xiàng)",如下所示:


3)當(dāng)用戶名或密碼錯(cuò)誤時(shí),提示“用戶名或密碼錯(cuò)誤",如下所示:


4)如果用戶名和密碼都正確,進(jìn)入主頁(index.html)。

既然有l(wèi)ogin,當(dāng)然要有l(wèi)ogout,logout比較簡(jiǎn)單,直接調(diào)用Django自帶用戶認(rèn)證系統(tǒng)的logout,然后返回登錄界面,具體如下(views.py):

@login_required
def logout(request):
  auth.logout(request)
  return HttpResponseRedirect("/accounts/login/")

上面@login_required表示只有用戶在登錄的情況下才能調(diào)用該視圖,否則將自動(dòng)重定向至登錄頁面。

urls.py里添加:

(r'^accounts/logout/$', 'dbrelease_app.views.logout'),

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

相關(guān)文章

  • Python如何給函數(shù)庫(kù)增加日志功能

    Python如何給函數(shù)庫(kù)增加日志功能

    這篇文章主要介紹了Python如何給函數(shù)庫(kù)增加日志功能,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-08-08
  • python自動(dòng)導(dǎo)入包的實(shí)現(xiàn)

    python自動(dòng)導(dǎo)入包的實(shí)現(xiàn)

    本文主要介紹了python自動(dòng)導(dǎo)入包的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • 使用sklearn對(duì)多分類的每個(gè)類別進(jìn)行指標(biāo)評(píng)價(jià)操作

    使用sklearn對(duì)多分類的每個(gè)類別進(jìn)行指標(biāo)評(píng)價(jià)操作

    這篇文章主要介紹了使用sklearn對(duì)多分類的每個(gè)類別進(jìn)行指標(biāo)評(píng)價(jià)操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • python?selenium中Excel數(shù)據(jù)維護(hù)指南

    python?selenium中Excel數(shù)據(jù)維護(hù)指南

    這篇文章主要給大家介紹了關(guān)于python?selenium中Excel數(shù)據(jù)維護(hù)的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2022-03-03
  • Python?Requests庫(kù)知識(shí)匯總

    Python?Requests庫(kù)知識(shí)匯總

    這篇文章主要介紹了Python?Requests庫(kù)學(xué)習(xí)總結(jié),本文通過示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-05-05
  • python實(shí)現(xiàn)定時(shí)任務(wù)的八種方式總結(jié)

    python實(shí)現(xiàn)定時(shí)任務(wù)的八種方式總結(jié)

    在日常工作中,我們常常會(huì)用到需要周期性執(zhí)行的任務(wù),下面這篇文章主要給大家介紹了關(guān)于python實(shí)現(xiàn)定時(shí)任務(wù)的八種方式,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-01-01
  • numpy 矩陣形狀調(diào)整:拉伸、變成一位數(shù)組的實(shí)例

    numpy 矩陣形狀調(diào)整:拉伸、變成一位數(shù)組的實(shí)例

    這篇文章主要介紹了numpy 矩陣形狀調(diào)整:拉伸、變成一位數(shù)組的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • Python多線程與異步處理在HTTP請(qǐng)求中的應(yīng)用方式

    Python多線程與異步處理在HTTP請(qǐng)求中的應(yīng)用方式

    這篇文章主要介紹了Python多線程與異步處理在HTTP請(qǐng)求中的應(yīng)用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • 查看Python安裝路徑幾種方法小結(jié)

    查看Python安裝路徑幾種方法小結(jié)

    這篇文章主要介紹了查看Python安裝路徑幾種方法小結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • python字符串排序方法

    python字符串排序方法

    這篇文章主要介紹了python字符串排序方法,基于lambda實(shí)現(xiàn),是非常實(shí)用的技巧,需要的朋友可以參考下
    2014-08-08

最新評(píng)論