• django 自定义auth中user登陆认证以及自写认证


    第一种:

    重写自定义auth中user登陆认证模块,

    引入MobelBackend

    from django.contrib.auth.backends import ModelBackend

    重写验证模块

    class CustomBackend(ModelBackend):
        def authenticate(self, request, username=None, password=None, **kwargs):
            try:
                user = Hbuser.objects.get(username=username)
                if user.is_staff :
                    if user.check_password(password):
                        return user
                    else:
                        return None
                return user
            except Exception as e:
                return None

    注意:user.is_staff 是默认是false,这样用户就不需要输入密码,直接返回None,本教程是用于用户跟项目登陆用户共用一张表,本项目不需要让用户输入密码,只输入用户名,即可登陆

    在setting里最下面设定如下:

    AUTHENTICATION_BACKENDS=('bao.views.CustomBackend',)

    注意:AUTHENTICATION_BACKENDS,必须是一个元组或者列表

    VIews.py中,可如下例子进行验证登陆,即不需要输入密码,只需要输入用户即可登陆

    class Login(View):
        def post(self,request):
            username=request.POST.get('username')
            user=authenticate(username=username, password=None)
            if user.is_authenticated:
                context={
                    'user':user
                }
                return render(request,'index.html',context)

    第二种:

    利用user.is_staff ,判断用户是否有登陆后台

    不需要写重写user登陆模块

    
    
    class Login(View):
    def post(self,request):
    username=request.POST.get('username')
    # user=authenticate(username=str(username), password=None)
    user=Hbuser.objects.filter(username=username).first()
    if not user.is_staff:
    print 'you xiao'
    context={
    'user':user
    }
    return render(request,'index.html',context)
    login(request,user)
     
  • 相关阅读:
    Java反射中Class.forName与classLoader的区别
    Java各种成员初始化顺序
    crontab python脚本不执行
    Java mybatis缓存(转)
    Java Synchronized及实现原理
    JVM类加载器
    SSH掉线问题
    SSH登陆远程卡、慢的解决的办法
    shell脚本执行python脚本时,python如何将返回值传给shell脚本
    使用scrapy进行数据爬取
  • 原文地址:https://www.cnblogs.com/weilaibuxiangshuo/p/10412803.html
Copyright © 2020-2023  润新知