首页 > 代码库 > django 的auth.authenticate返回为None

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!!"})


折磨我好几个晚上~~~

 

django 的auth.authenticate返回为None