Django中authenticate和login模塊


Django 提供內置的視圖(view)函數用於處理登錄和退出,Django提供兩個函數來執行django.contrib.auth中的動作 : authenticate()和login()。

認證給出的用戶名和密碼,使用 authenticate() 函數。它接受兩個參數,用戶名 username 和 密碼 password ,並在密碼對給出的用戶名合法的情況下返回一個 User 對象。 如果密碼不合法,authenticate()返回None。

>>> from django.contrib import auth
>>> user = auth.authenticate(username='john', password='secret')
>>> if user is not None:
...   print "Correct!"
... else:
...   print "Invalid password."

登錄和驗證

authenticate() 只是驗證一個用戶的證書而已。 而要登錄一個用戶,使用 login() 。該函數接受一個 HttpRequest 對象和一個 User 對象作為參數並使用Django的會話( session )框架把用戶的ID保存在該會話中。

下面的例子演示了如何在一個視圖中同時使用 authenticate() 和 login() 函數:

from django.contrib import auth

def login_view(request):
  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:
    # Correct password, and the user is marked "active"
    auth.login(request, user)
    # Redirect to a success page.
    return HttpResponseRedirect("/account/loggedin/")
  else:
    # Show an error page
    return HttpResponseRedirect("/account/invalid/")

在這里,有個有意思的是user.is_active,用來判斷用戶名密碼是否有效。

注銷用戶

注銷一個用戶,在你的視圖中使用django.contrib.auth.logout() 。 它接受一個HttpRequest對象並且沒有返回值,所以,因為沒有返回值,需要返回一個頁面

from django.contrib import auth
 
def logout_view(request):
  auth.logout(request)
  # Redirect to a success page.
  return HttpResponseRedirect("/account/loggedout/")

需要注意的是:即使用戶沒有登錄, logout() 也不會拋出任何異常

Django中常規登錄和退出函數用法

在實際中,你一般不需要自己寫登錄/登出的函數;認證系統提供了一系例視圖用來處理登錄和登出。 使用認證視圖的第一步是把它們寫在你的URLconf中。 你需要這樣寫:

from django.contrib.auth.views import login, logout
 
urlpatterns = patterns('',
  # existing patterns here...
  (r'^accounts/login/$', login),
  (r'^accounts/logout/$', logout),
)

/accounts/login//accounts/logout/ 是Django提供的視圖的默認URL。

登錄頁面的寫法

缺省情況下, login 視圖渲染 registragiton/login.html 模板(可以通過視圖的額外參數 template_name 修改這個模板名稱)。 這個表單必須包含 username 和 password 域。如下示例: 一個簡單的 template 看起來是這樣的

{% extends "base.html" %}
 
{% block content %}
 
 {% if form.errors %}
  <p class="error">Sorry, that's not a valid username or password</p>
 {% endif %}
 
 <form action="" method="post">
  <label for="username">User name:</label>
  <input type="text" name="username" value="" id="username">
  <label for="password">Password:</label>
  <input type="password" name="password" value="" id="password">
 
  <input type="submit" value="login" />
  <input type="hidden" name="next" value="{{ next|escape }}" />
 </form>
 
{% endblock %}

如果用戶登錄成功,缺省會重定向到 /accounts/profile 你可以提供一個保存登錄后重定向URL的next隱藏域來重載它的行為。 也可以把值以GET參數的形式發送給視圖函數,它會以變量next的形式保存在上下文中,這樣你就可以把它用在隱藏域上了。

logout視圖有一些不同。 默認情況下它渲染 registration/logged_out.html 模板(這個視圖一般包含你已經成功退出的信息)。 視圖中還可以包含一個參數 next_page 用於退出后重定向。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM