• django 的auth.authenticate返回为None


    使用auth.authenticate(username= username,passowrd=passowrd),这个用户认证时候,明明数据库中有记录,但是返回就None

    我的错误点比较多:

    1.我创建的用户名和密码,并没有添加到在auth_user(django自带的表)中,而是放进了通过modely映射生成的表,从而导致auth.authenticate()根本查不到响应的数据

    2.插入数据用户名密码时应该用User.objects.create_user(username=username,password=password),这个方法会把密码生成哈希值,插进数据库,而不能用User.objects.create(。。。。),这样插进去的数据密码是明文滴~~~~

    总结:用对方法User.objects.create_user(username=username,password=password),插对表user

    下面是调用注册和登录的代码:

    #coding = utf-8
    from django.shortcuts import render
    from django.http import JsonResponse
    import time
    from django.views.decorators.csrf import csrf_exempt
    from sign1.models import smile_task_user
    from django.core.exceptions import ValidationError
    from django.contrib import auth
    from django.contrib.auth.models import User
    
    
    
    #注册接口POST /register username/password
    @csrf_exempt
    def register(request):
    
        username = request.POST.get('username','')
        password = request.POST.get('password','')
        regist_time = time.strftime("%Y-%m-%d %H:%M:%S")
    
        if username=="" or password =="" :
            return JsonResponse({'message':'username or passowrd is null !!!'})
        
        result = User.objects.filter(username = username)
        if result:
            return JsonResponse({'message':'username is already exists !!!'})
    
        try:
            User.objects.create_user(username=username,password=password)
            
        except ValidationError as e:
            error = "####create data worng#############"
            return JsonResponse({'ststus':10024,'message':error})
        return JsonResponse({'username':username,'regist_time':regist_time,'message':'regist ok!'})
    
    #登录接口POST /login username/password
    @csrf_exempt
    def login(request):
        if request.method =="POST":
            username=request.POST.get("username","")
            password=request.POST.get("password","")
    
            user=auth.authenticate(username=username,password=password)
            print(user)
            #user = smile_task_user.objects.filter(username = username,password = password)
            if user is not None:
                    auth.login(request,user)
                    request.session['user'] = username # 将 session 信息记录到浏览器
                    return JsonResponse({'message':"login sucess"})
            else:
                return JsonResponse({'message':"username or password is error!!"})


    折磨我好几个晚上~~~

  • 相关阅读:
    运算符、基本数据类型-----整型、字符串
    练习题
    python安装与初识(python起源、分类,if语句、while语句、基本数据类型、变量的命名)
    hdu2187悼念512汶川大地震遇难同胞——老人是真饿了(贪心 简单题)
    牛客小白月赛9 A签到(分数取模,逆元)
    牛客小白月赛9H论如何出一道水题(两个连续自然数互质)
    EOJ3134. 短信激活码(大数幂取模)
    EOJ3650 转机折扣(26进制,字符串)
    hdu1042 N!(大数求阶乘)
    hdu2061 Treasure the new start, freshmen!(暴力简单题)
  • 原文地址:https://www.cnblogs.com/imtester/p/6023994.html
Copyright © 2020-2023  润新知