在搭建網站和web的應用程序時,用戶的登錄和管理是幾乎是每個網站都必備的。今天主要從一個實例了解以下django本身自帶的user模塊。本文並不對user進行擴展。
主要使用原生的模塊。
1.User模塊基礎:
在使用user 之前先import到自己的iew中。相當與我們自己寫好的models。只不過這個是系統提供的models。
from django.contrib.auth.models import User # 導入user模塊
1.1User對象屬性
User 對象屬性:username
, password
(必填項)password
用哈希算法保存到數據庫
email
,last_login
,date_joined
(字面意思就知道了)
is_staff
: 用戶是否擁有網站的管理權限.
is_active
: 是否允許用戶登錄, 設置為False
,可以不用刪除用戶來禁止 用戶登錄
1.2User 對象方法
is_authenticated()
: 如果是真正的 User 對象,返回值恆為 True 。 用於檢查用戶是否已經通過了認證。通過認證並不意味着 用戶擁有任何權限,甚至也不檢查該用戶是否處於激活狀 態,這只是表明用戶成功的通過了認證。
這個方法很重要, 在后台用request.user.is_authenticated()判斷用戶是否已經登錄,如果true則可以向前台展示request.user.name
set_password(passwd)
這個方法是用來更改密碼的,先用
user=User.objects.get(username='')
user.set_password(passeord='')
user.save
check_password(passwd)
用戶需要修改密碼的時候 首先要讓他輸入原來的密碼 ,如果給定的字符串通過了密碼檢查,返回 True
email_user(subj, msg)
給用戶發送電子郵件,用 DEFAULT_FROM_EMAIL
的設 置作為發件人。也可以用第3個參數 from_email
來 覆蓋設置。
1.3;創建User用戶
使用 create_user
輔助函數創建用戶:
from django.contrib.auth.models import User
user = User.objects.create_user(username='',password='',email='')
user.save 注意這里不是save()!
1.4. 登錄和認證
Django 在 django.contrib.auth
中提供了兩個函數來處理這些事情—— authenticate()
和 login()
authenticate()
: 認證給出的用戶名和密碼,使用 authenticate() 函數。它接受兩個參數,用戶名 username 和 密碼 password ,並在密碼對用給出的用戶名是合法的情況下返回一個 User 對象。當給出的密碼不合法的時候 authenticate() 函數返回 None
login()
:該函數接受一個 HttpRequest
對象和一個 User
對象作為參數並使用Django的會話( session )框架把用戶的ID保存在該會話中
from django.contrib import auth
user = auth.authenticate(username=username, password=password)
if user:
auth.login(request, user)
1.5.注銷和重定向
注銷 logout()
該函數接受一個 HttpRequest
對象作為參數,沒有返回值
auth.logout(request)
重定向:HttpResponseRedirect()
該函數主要實現,url的重定向。
在我們登錄和注銷后,重定向到指定url。該函數可以采用url的硬編碼。
return HttpResponseRedirect('/sbook/sb_show')
2.實現用戶注冊和登錄
通過上面的基礎知識,我們已經了解如何創建和更新一個user啦。接下來用一個實例來做一下用戶的注冊和登錄。
案子mvc的模型,系統已經提供了model,所以我們要做的只需要實現iew和template就行了。在view.py 中實現對注冊和登錄的控制。
先看以下view中的代碼
# 登錄視圖模塊
def alogin(request):
errors= []
account=None
password=None
if request.method == 'POST' :
if not request.POST.get('account'):
errors.append('請輸入帳戶!Please Enter account!')
else:
account = request.POST.get('account')
if not request.POST.get('password'):
errors.append('請輸入密碼!Please Enter password!')
else:
password= request.POST.get('password')
if account is not None and password is not None :
user = authenticate(username=account,password=password)
if user is not None:
if user.is_active:
login(request,user)
# 登錄成功,頁面跳轉!
return HttpResponseRedirect('/index')
else:
errors.append('禁用帳戶!disabled account!')
else :
errors.append('隱藏用戶!invaild user!')
# 非post登錄請求,跳轉到登錄頁面!
return render_to_response('account/login.html', {'errors': errors})
# 用戶注冊視圖模塊
def register(request):
errors= []
account=None
password=None
password2=None
email=None
CompareFlag=False
if request.method == 'POST':
if not request.POST.get('account'):
errors.append('請輸入帳戶!Please Enter account!')
else:
account = request.POST.get('account')
if not request.POST.get('password'):
errors.append('請輸入密碼!Please Enter password!')
else:
password= request.POST.get('password')
if not request.POST.get('password2'):
errors.append('請輸入密碼2!Please Enter password2!')
else:
password2= request.POST.get('password2')
if not request.POST.get('email'):
errors.append('請輸入電子郵件!Please Enter email!')
else:
email= request.POST.get('email')
if password is not None and password2 is not None:
if password == password2:
CompareFlag = True
else :
errors.append('兩次輸入的密碼不同!password2 is diff password!')
if account is not None and password is not None and password2 is not None and email is not None and CompareFlag :
user=User.objects.create_user(account,email,password)
user.is_active=True
user.save
# 注冊成功后跳轉
return HttpResponseRedirect('/account/login')
# 注冊失敗跳轉到新的注冊頁面,並提示錯誤!
return render_to_response('account/register.html', {'errors': errors})
# 注銷登錄,退出賬號
def alogout(request):
logout(request)
# 退出后跳轉頁面
return HttpResponseRedirect('/index')
從以上的代碼中,我們是在template里創建的form。
在templates下創建account目錄。在下面創建login.html
<!DOCTYPE html>
<html>
<head>
<title>歡迎登錄!Welcome login!</title>
</head>
<body>
<p>帳戶登錄 Account Login</p>
{% if errors %}
<li>
{% for error in errors %}
<p style="color: red;">
請更正錯誤:{{error}} .
Please correct the error: {{error}} below.
</p>
{% endfor %}
</li>
{% endif %}
<form action="" method="post">
<input type = 'text' placeholder="Please input account" name="account">
<br>
<input type = 'password' placeholder="Please input password" name="password">
<br>
<input type = 'submit' placeholder="Login" value="Login">
<br>
<a href="/account/register">注冊新帳戶 register new accout</a>
</form>
</body>
</html>
同樣的方式創建register.html
<html>
<head>
<title>歡迎注冊新帳戶!Welcome Register New Account!</title>
</head>
<body>
{% if errors %}
<li>
{% for error in errors %}
<p style="color: red;">
請更正下面的錯誤:{{error}}。
Please correct the error: {{error}} below.
</p>
{% endfor %}
</li>
{% endif %}
<table>
<form action="" method="post">
<tr>
<td>
<label >帳戶 Account:</label>
</td>
<td>
<input type = 'text' placeholder="Please input account" name = 'account'>
</td>
</tr>
<tr>
<td>
<label >密碼 Password:</label>
</td>
<td>
<input type = 'password' placeholder="Please input password" name = 'password'>
</td>
</tr>
<tr>
<td>
<label >密碼 Password:</label>
</td>
<td>
<input type = 'password' placeholder="Please input password" name ='password2'>
</td>
</tr>
<tr>
<td>
<label>email:</label>
</td>
<td>
<input type="email" placeholder="Please input email" name = 'email'>
</td>
</tr>
<tr>
<td>
<input type = 'submit' placeholder="Login" value="Login">
</td>
</tr>
</form>
</table>
</body>
</html>
接下來view和template創建好了,只有床urls的映射關系啦。
url(r'^account/login/$', alogin),
url(r'^account/register/$', register),
url(r'^account/logout/$', alogout),
ok到此為止,用戶的注冊和登錄就可以在在瀏覽器上看到效果啦。