Django3.0.4用户认证系统authenticate()一直返回None

 win7 下 python3.7.4 +Django3.0.4

我使用Django内部的User认证系统,本以为User.objects.create_user(username,password,email)加密及存入注册,使用user=auth.authenticate(username=username,password=password)解密并登陆,但反复auth.authenticate()测试,均返回none,在csdn中看了别人的文章,使用 check_password(password,pwd),还是返回none,查了UserManager下create_user()加密使用set_password()来加密的,经测试 check_password(password,pwd)不一致,可能是个bug,没有办法,只能在注册中加入user.set_password(password),问题解决!代码如下:

注册:

class RegisterViews(View):
    def get(self,request):
        print("get")
        return render(request,'register.html')

    def post(self,request):
        print("post")
        username = request.POST.get('user_name')
        password = request.POST.get('pwd')
        password1 = request.POST.get('cpwd')
        email = request.POST.get('email')
        allow = request.POST.get('allow')

        if not all([username,password,password1,email]):
            return render(request, 'register.html', {'errmsg':'要素填写不全'})

        if allow != 'on':
            return render(request, 'register.html',{'errmsg':'用户使用协议未勾选'})

        if password != password1:
            return render(request, 'register.html',{'errmsg':'两次密码输入不一致'})

        if not re.match('^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$',email):
            return render(request, 'register.html', {'errmsg':'邮箱格式有误'})

        try:
            User.objects.get(username=username)
            return render(request, 'register.html', {'errmsg': '用户已注册'})
        except ObjectDoesNotExist as e:
            user=User.objects.create_user(username,password,email)
            user.is_active=0
            print("++++++++++++++")
            print(user.password)
            user.set_password(password)
            print(user.password)
            print("++++++++++++++")
            user.save()


        return render(reverse('user:login'))

登陆:

class LoginViews(View):

    def get(self, request):
        return render(request, 'login.html')

    def post(self,request):
        username=request.POST.get("username")
        password = request.POST.get("pwd")

        if not all([username,password]):
            return render(request, 'login.html', {'errmsg': '要素填写不全!'})
        print(username,password)
        #user=auth.authenticate(username=username,password=password)

        try:
            user=User.objects.get(username=username)
        except User.DoesNotExist:
            return render(request, 'login.html', {'errmsg': '用户不存在!'})

        pwd=user.password
        pwd1=make_password(password)
        print(pwd,pwd1)
        if check_password(password,pwd):
            print('ok')
            return render(request, 'list.html')

        else:
            print('error')
            return render(request, 'login.html', {'errmsg': '用户名或者密码错误!'})

 

参考文章:https://blog.csdn.net/joe8910/article/details/82658183

你可能感兴趣的:(Django3.0.4用户认证系统authenticate()一直返回None)