python django rest framework authenticate keep返回NONE

dwbf0jvd  于 2023-05-27  发布在  Python
关注(0)|答案(1)|浏览(146)

authenticate保持不返回,即使我确定从数据库中的名称和密码,我写他们的权利。我也检查了这些问题,12,但没有帮助。这是我代码。views.py

@api_view(['POST'])
def user_login(request):
    print("im in login")
    print(request)

    if request.method == 'POST':
        name = request.data.get('name')
        password = request.data.get('password')
        print("username : ",name,"password : ",password)
        user = authenticate(username=name, password=password)
        print("user : ",user)
        if user is not None:
            # Authentication successful
            login(request, user)
            return Response({'message': 'Login successful'})

        else:
            # Authentication failed
            return Response({'message': 'Invalid credentials'})

    else:
        # Render the login form
        return   Response({'message': 'Invalid request method'})

serializer.py :

def create(self, validated_data):
    user = user_auth.objects.create(
        email=validated_data['email'],
        name=validated_data['name'],
        password = make_password(validated_data['password'])
    )
    return user

models.py

class user_auth(models.Model):
    name = models.CharField(max_length=80)
    email = models.EmailField()
    password = models.CharField(max_length=15)
    created = models.DateField(auto_now_add=True)

这是数据库中的散列密码


我不知道我做错了什么。

4dbbbstv

4dbbbstv1#

我让它工作,这是我改变的。首先,我在设置中添加了这一行,如果你没有添加它,authenticate by defaul将尝试在auth_user中搜索用户,而不是在你的自定义用户中搜索:

`AUTH_USER_MODEL = 'base.user_auth'` (change base by the name of your app).

第二件事,我不得不通过继承AbstractUser而不是model.Model来更改模型(我还添加了username字段和unicod函数,即使我不认为它们是如此必要):

class user_auth(AbstractUser):
    email = models.EmailField()
    password = models.CharField(max_length=15)
    created = models.DateField(auto_now_add=True)
    USERNAME_FIELD = 'username'
    def __unicode__(self):
        return self.username.

和序列化程序没有改变任何东西。

相关问题