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

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

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

上一篇中,我們已經打開了Django自帶的用戶認證模塊,并配置了數(shù)據(jù)庫連接,創(chuàng)建了相應的表,本篇我們將在Django自帶的用戶認證的基礎上,實現(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è)務邏輯是:

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比較簡單,直接調用Django自帶用戶認證系統(tǒng)的logout,然后返回登錄界面,具體如下(views.py):

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

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

urls.py里添加:

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論

千阳县| 喀喇| 新泰市| 扶绥县| 江城| 恩平市| 衡阳县| 安化县| 锦屏县| 鄯善县| 始兴县| 基隆市| 申扎县| 前郭尔| 陕西省| 察隅县| 温宿县| 台南县| 文昌市| 饶阳县| 保德县| 松江区| 安庆市| 青阳县| 手机| 铜川市| 罗甸县| 贵州省| 修水县| 北票市| 苍梧县| 昭苏县| 香格里拉县| 马鞍山市| 和静县| 塔河县| 岚皋县| 遂溪县| 安平县| 铜川市| 辽源市|