亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

Django學習筆記(6-2 用戶登錄-2)

標簽:
Python
  • 两个login
def login(request):
    ......
    if user is not None:
        #这里会报错,因为有两个login,所以很重要的一点,函数名称不要和默认名称一样。否则就会使用混乱。否则就要写全路径
        #这也说明了python的函数可以自己调用自己
        login(request,user)
        return render(request,"index.html")
    else:
        return render(request,"login.html")
    ......

改为

def user_login(request):

在session有效期内,即使没有登陆也会自动登陆

  • 自定义后台auth的认证方法
    重写authenticate,以后user_login函数里面的authenticated验证就是我们自己写的了,而也不用更改user_login方法
from django.contrib.auth.backends import ModelBackend
from .models import UserProfile

class CustomBackend(ModelBackend):
    def authenticate(self,username=None,password=None,**kwargs):
        try:
            user = UserProfile.objects.get(username=username)
            #password是密文,so,不能password=password,因为用户输入的是明文呀
            #userprofile继承了adstractuser,所以有个check_password方法
            if user.check_password(password):
                return user
            except Exception as e:
                return None
  • 把自定义的验证逻辑注册

setting.py

AUTHENTICATION_BACKENDS = (
    ‘users.views.CustomBackend',
       #注意一定要加“,”特别是元组数据的时候
)
  • 让email也可以登陆
    现在就可以在自定义的au里面写点自己的逻辑了
user = UserProfile.objects.get(username=username,)
#,是并集

username和eamil登陆是“或”关系,现在介绍Q

user = UserProfile.objects.get(Q(username=username)|Q(email=username),Q(password=password))
#并非全是并集,而是并集与交集的随意排版
#把password去掉
user = UserProfile.objects.get(Q(username=username)|Q(email=username))
  • 提示登陆错误
def login(request):
    ......
    if user is not None:
        login(request,user)
        return render(request,"index.html")
    else:
        return render(request,"login.html",{"msg":"用户名或密码错误"})
    ......

{{ msg }}

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消