Django 認證

from django.contrib import auth

1.authenticate()css

提供了用戶認證,即驗證用戶名以及密碼是否正確,通常須要username和password兩個關鍵字參數html

若是經過認證,authenticate()函數會返回一個User對象,沒經過返回Nonedocker

user=authenticate(username="uaername",password="password"

2.login(request)登錄用戶數據庫

這個函數使用Djangosession框架給某個已認證的用戶附加上session_id信息。django

使用:session

    from django.shortcuts import render,redirect,HttpResponse
    
    from django.contrib.auth import authenticate,login
    
    def auth_view(request):
        username=request.POST.GET("usernmae")       # 獲取用戶名
        password=request.POST.GET("password")       # 獲取用戶的密碼
    
        user=authenticate(username=username,password=password)  # 驗證用戶名和密碼,返回用戶對象
    
        if user:                        # 若是用戶對象存在
            login(request,user)         # 用戶登錄
            return redirect("/index/")
    
        else:
            return HttpResponse("用戶名或密碼錯誤")

 

3.logout(request)註銷用戶框架

這個函數接受一個HttpResponse對象,無返回值。dom

當調用該函數時,當前請求的session信息所有被清除。函數

即便當前用戶沒有登錄,調用該函數也不會報錯。post

    from django.shortcuts import render,redirect,HttpResponse    
    from django.contrib.auth import authenticate,login,logout
    
    def logout_view(request):       
        logout(request)     # 註銷用戶       
        return redirect("/index/")

 

4.user對象

User對象屬性:username,password爲必填項

  • is_staff:判斷用戶是否擁有網站的管理權限
  • is_active:判斷是否容許用戶登錄,設置爲「False」時能夠不用刪除用戶來禁止用戶登錄
  • User對象的屬性值能夠在template裏取得,如:request.user.username request.user.mobile request.user.is_staff

 

5.user對象的is_authenticated()

要求:

  • 用戶登錄後才能訪問某些頁面
  • 若是用戶沒有登錄就訪問本應登錄才能訪問的頁面時會直接跳轉到登錄頁面
  • 用戶在登錄頁面登錄後,又會自動跳轉到以前訪問的頁面

方法一:

    def view1(request):        
        if not request.user.is_authenticated():
            return redirect("/login/")

方法二:

 # login_required裝飾器
 from django.contrib.auth.decorators import login_required
    @login_required
    def views(request):
        pass

若是用戶沒有登錄,則會跳轉到Django默認的登錄URL的"/accountss/login/"

login視圖函數能夠在settings.py文件中經過LOGIN_URL修改默認


6.建立用戶 create_user

    from django.contrib.auth.models import User
    
    user=User.objects.get(username="username")      # 獲取用戶對象
    user.set_password(password="password")          # 設置對象的密碼   
    user.save()

 

7.修改密碼check_password(password)

    from django.shortcuts import render,redirect,HttpResponse
    from django.contrib.auth import authenticate,login,logout
    from django.contrib.auth.decorators import login_required
    from django.contrib.auth.models import User
    
    @login_required
    def change_passwd(request):
        user=request.user       # 獲取用戶名
        msg=None
    
        if request.method=='POST':
            old_password=request.POST.get("old_password","")    # 獲取原來的密碼,默認爲空字符串
            new_password=request.POST.get("new_password","")    # 獲取新密碼,默認爲空字符串
            confirm=request.POST.get("confirm_password","")     # 獲取確認密碼,默認爲空字符串
    
            if user.check_password(old_password):               # 到數據庫中驗證舊密碼經過
                if new_password or confirm:                     # 新密碼或確認密碼爲空
                    msg="新密碼不能爲空"   
                elif new_password != confirm:                   # 新密碼與確認密碼不同
                    msg="兩次密碼不一致"
    
                else:
                    user.set_password(new_password)             # 修改密碼
                    user.save()
    
                    return redirect("/index/")
            else:
                msg="舊密碼輸入錯誤"
    
        return render(request,"change_passwd.html",{"msg":msg})


 

7.修改密碼check_password(password)

方式一

from django.shortcuts import render,redirect,HttpResponse
    from django.contrib.auth import authenticate,login,logout
    from django.contrib.auth.decorators import login_required
    from django.contrib.auth.models import User
    
    @login_required
    def change_passwd(request):
        user=request.user       # 獲取用戶名
        msg=None
    
        if request.method=='POST':
            old_password=request.POST.get("old_password","")    # 獲取原來的密碼,默認爲空字符串
            new_password=request.POST.get("new_password","")    # 獲取新密碼,默認爲空字符串
            confirm=request.POST.get("confirm_password","")     # 獲取確認密碼,默認爲空字符串
    
            if user.check_password(old_password):               # 到數據庫中驗證舊密碼經過
                if new_password or confirm:                     # 新密碼或確認密碼爲空
                    msg="新密碼不能爲空"   
                elif new_password != confirm:                   # 新密碼與確認密碼不同
                    msg="兩次密碼不一致"
    
                else:
                    user.set_password(new_password)             # 修改密碼
                    user.save()
    
                    return redirect("/index/")
            else:
                msg="舊密碼輸入錯誤"
    
        return render(request,"change_passwd.html",{"msg":msg})

方式二

# 經過form檢測和認證
# 認證forms表單
from django import forms

class ChangePasswordForm(forms.Form):
    old_password = forms.CharField(label=u'原密碼', error_messages={'required': '請輸入原始密碼'},
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'style': 'width:500px;'}))
    new_password1 = forms.CharField(label=u'新密碼', error_messages={'required': '請輸入新密碼'},
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'style': 'width:500px;'}))
    new_password2 = forms.CharField(label=u'新密碼', error_messages={'required': '請重複新輸入密碼'},
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'style': 'width:500px;'}))

    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(ChangePasswordForm, self).__init__(*args, **kwargs)

    def clean_old_password(self):
        old_password = self.cleaned_data["old_password"]
        if not self.user.check_password(old_password):
            raise forms.ValidationError(u'原密碼錯誤')
        return old_password

    def clean_new_password2(self):
        password1 = self.cleaned_data.get('new_password1')
        password2 = self.cleaned_data.get('new_password2')
        if len(password1)<6:
            raise forms.ValidationError(u'密碼必須大於6位')

        if password1 and password2:
            if password1 != password2:
                raise forms.ValidationError(u'兩次密碼輸入不一致')
        return password2

    def save(self, commit=True):
        self.user.set_password(self.cleaned_data['new_password1'])
        if commit:
            self.user.save()
        return self.user


# 改密碼html
<form class="form-horizontal" role="form" method="post" action={% url "change_password" %}>
    {% csrf_token %}
              <div class="box-body">
        {% for item in form %}
            <div class="form-group">
                <label class="col-sm-1 control-label">{{item.label}}</label>

                <div class="col-ms-8" style="margin-left: 10px;">
                    {{item}}
                </div>
                <div class="col-ms-8" style="margin-left: 10px;">
                    {{item.errors}}
                </div>
            </div>
        {% endfor %}
        <div class="form-group">
            <div class="box-footer" style="margin-left: 10px;width: 530px;">
                <button type="submit" class="btn btn-primary pull-left" style="width: 120px">更新密碼</button>&nbsp;&nbsp;
            </div>
        </div>
              </div>
    </form>

# 更改密碼函數
@login_required()
def change_password(request):
    if request.method == 'POST':
        form = ChangePasswordForm(user=request.user, data=request.POST)
        u = form.user
        if form.is_valid():
            form.save()
            return HttpResponse(str(u)+"密碼更新成功!")
    else:
        form = ChangePasswordForm(user=request.user)
    kwargs = {
        'form': form,
        'request': request,
    }
    return render(request, 'accounts/change_password.html', kwargs)

 

8.引用用戶模型get_user_model()

get_user_model().objects能夠操做用戶表user

#顯示全部用戶
get_user_model().objects.all()

#刪除用戶
get_user_model().objects.filter(id=用戶id).delete()

#隨機生成10位數密碼
get_user_model().objects.make_random_password(length=10, allowed_chars='abcdefghjklmnpqrstuvwxyABCDEFGHJKLMNPQRSTUVWXY3456789')

 

 

CP https://www.cnblogs.com/ccorz/p/Django-zi-ding-yi-yong-hu-ren-zheng-xi-tong-zhi-zi.htmlhttps://www.cnblogs.com/renpingsheng/p/7629997.htmlhttps://www.cnblogs.com/ccorz/p/6358074.html
相關文章
相關標籤/搜索