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

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

 更新時間:2018年07月16日 10:44:38   作者:Zhu_Julian  
這篇文章主要介紹了Django實戰(zhàn)之用戶認證(用戶登錄與注銷),小編覺得挺不錯的,現(xià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如何給函數(shù)庫增加日志功能

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

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

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

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

    使用sklearn對多分類的每個類別進行指標評價操作

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

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

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

    Python?Requests庫知識匯總

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

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

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

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

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

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

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

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

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

    python字符串排序方法

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

最新評論