Django的用戶登錄模塊User


在搭建網站和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中的代碼

 

[python] view plain copy
print ? 在CODE上查看代碼片 派生到我的代碼片
  1. def alogin(request):  
  2.     errors= []  
  3.     account=None  
  4.     password=None  
  5.     if request.method == 'POST' :  
  6.         if not request.POST.get('account'):  
  7.             errors.append('Please Enter account')  
  8.         else:  
  9.             account = request.POST.get('account')  
  10.         if not request.POST.get('password'):  
  11.             errors.append('Please Enter password')  
  12.         else:  
  13.             password= request.POST.get('password')  
  14.         if account is not None and password is not None :  
  15.              user = authenticate(username=account,password=password)  
  16.              if user is not None:  
  17.                  if user.is_active:  
  18.                      login(request,user)  
  19.                      return HttpResponseRedirect('/index')  
  20.                  else:  
  21.                      errors.append('disabled account')  
  22.              else :  
  23.                   errors.append('invaild user')  
  24.     return render_to_response('account/login.html', {'errors': errors})  
  25. def register(request):  
  26.     errors= []  
  27.     account=None  
  28.     password=None  
  29.     password2=None  
  30.     email=None  
  31.     CompareFlag=False  
  32.   
  33.     if request.method == 'POST':  
  34.         if not request.POST.get('account'):  
  35.             errors.append('Please Enter account')  
  36.         else:  
  37.             account = request.POST.get('account')  
  38.         if not request.POST.get('password'):  
  39.             errors.append('Please Enter password')  
  40.         else:  
  41.             password= request.POST.get('password')  
  42.         if not request.POST.get('password2'):  
  43.             errors.append('Please Enter password2')  
  44.         else:  
  45.             password2= request.POST.get('password2')  
  46.         if not request.POST.get('email'):  
  47.             errors.append('Please Enter email')  
  48.         else:  
  49.             email= request.POST.get('email')  
  50.   
  51.         if password is not None and password2 is not None:  
  52.             if password == password2:  
  53.                 CompareFlag = True  
  54.             else :  
  55.                 errors.append('password2 is diff password ')  
  56.   
  57.   
  58.         if account is not None and password is not None and password2 is not None and email is not None and CompareFlag :  
  59.             user=User.objects.create_user(account,email,password)  
  60.             user.is_active=True  
  61.             user.save  
  62.             return HttpResponseRedirect('/account/login')  
  63.   
  64.   
  65.     return render_to_response('account/register.html', {'errors': errors})  
  66.   
  67. def alogout(request):  
  68.     logout(request)  
  69.     return HttpResponseRedirect('/index')  
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')
    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('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

 

[python] view plain copy
print ? 在CODE上查看代碼片 派生到我的代碼片
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>Welcome login </title>  
  5. </head>  
  6. <body>  
  7.     <p>Account Login </p>  
  8.   
  9.     {% if errors %}  
  10.         <li>  
  11.             {% for error in errors %}  
  12.              <p style="color: red;">  
  13.                 Please correct the error: {{error}} below.  
  14.              </p>  
  15.               {% endfor %}  
  16.         </li>  
  17.     {% endif %}  
  18.   
  19.     <form action="" method="post">  
  20.         <input type = 'text' placeholder="Please input account" name="account">  
  21.        <br>  
  22.   
  23.         <input type = 'password' placeholder="Please input password" name="password">  
  24.         <br>  
  25.         <input type = 'submit' placeholder="Login" value="Login">  
  26.         <br>  
  27.         <a href="/account/register">register new accout</a>  
  28.     </form>  
  29. </body>  
  30. </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;">
                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

 

 

  1. <html>  
  2. <head>  
  3.     <title>Welcome Register New Account</title>  
  4. </head>  
  5. <body>  
  6.   
  7.  {% if errors %}  
  8.         <li>  
  9.   
  10.             {% for error in errors %}  
  11.              <p style="color: red;">  
  12.                 Please correct the error: {{error}} below.  
  13.              </p>  
  14.               {% endfor %}  
  15.         </li>  
  16.     {% endif %}  
  17. <table>  
  18.     <form action="" method="post">  
  19.         <tr>  
  20.             <td>  
  21.                 <label >Account:</label>  
  22.             </td>  
  23.             <td>  
  24.                 <input type = 'text' placeholder="Please input account" name = 'account'>  
  25.             </td>  
  26.         </tr>  
  27.         <tr>  
  28.             <td>  
  29.                 <label >Password:</label>  
  30.             </td>  
  31.             <td>  
  32.               <input type = 'password' placeholder="Please input password" name = 'password'>  
  33.             </td>  
  34.         </tr>  
  35.          <tr>  
  36.              <td>  
  37.                 <label >Password:</label>  
  38.              </td>  
  39.              <td>  
  40.                  <input type = 'password' placeholder="Please input password" name ='password2'>  
  41.              </td>  
  42.   
  43.          </tr>  
  44.          <tr>  
  45.              <td>  
  46.                  <label>email:</label>  
  47.              </td>  
  48.              <td>  
  49.                  <input type="email" placeholder="Please input email" name = 'email'>  
  50.              </td>  
  51.          </tr>  
  52.           <tr>  
  53.   
  54.               <td>  
  55.                    <input type = 'submit' placeholder="Login" value="Login">  
  56.               </td>  
  57.           </tr>  
  58.     </form>  
  59. </table>  
  60. </body>  
  61. </html>  
<html>
<head>
    <title>Welcome Register New Account</title>
</head>
<body>

 {% if errors %}
        <li>

            {% for error in errors %}
             <p style="color: red;">
                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的映射關系啦。

 

 

[python] view plain copy
print ? 在CODE上查看代碼片 派生到我的代碼片
  1. url(r'^account/login/$', alogin),  
  2.    url(r'^account/register/$', register),  
  3.    url(r'^account/logout/$', alogout),  
 url(r'^account/login/$', alogin),
    url(r'^account/register/$', register),
    url(r'^account/logout/$', alogout),

ok到此為止,用戶的注冊和登錄就可以在在瀏覽器上看到效果啦。

 






 


免責聲明!

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



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