为了账号安全,请及时绑定邮箱和手机立即绑定

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下载
官方微信

举报

0/150
提交
取消