Django REST框架验证一直返回NONE。

huangapple go评论74阅读模式
英文:

django rest framework authenticate keep returning NONE

问题

Here's the translation of the code portion you provided:

身份验证一直返回None即使我确保数据库中的用户名和密码是正确的我也检查了这些问题[1]和[2]但没有帮助
以下是我的代码
views.py

@api_view(['POST'])
def user_login(request):
    print("我在登录")
    print(request)

    if request.method == 'POST':
        name = request.data.get('name')
        password = request.data.get('password')
        print("用户名:", name, "密码:", password)
        user = authenticate(username=name, password=password)
        print("用户:", user)
        if user is not None:
            # 验证成功
            login(request, user)
            return Response({'message': '登录成功'})

        else:
            # 验证失败
            return Response({'message': '无效的凭据'})

    else:
        # 渲染登录表单
        return Response({'message': '无效的请求方法'})
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)

这是数据库中的哈希密码
[![在此输入图片描述][3]][3]
我不知道我做错了什么

[1]: https://stackoverflow.com/questions/15557196/authenticate-always-returns-none?rq=3
[2]: https://stackoverflow.com/questions/18778061/authenticate-function-not-working-django-contrib-auth
[3]: https://i.stack.imgur.com/0ckHs.jpg

Please note that the translation is provided for the code portion only, as per your request.

英文:

authenticate keep returning none even I'm sure from the name and the password in database and I write them right . I also check these questions, 1 and 2 but didn't help .
here is my code .
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)

here is the hashed password in database

Django REST框架验证一直返回NONE。
I don't know what I did wrong .

答案1

得分: 0

我已经让它工作了,以下是我所做的更改:

首先,我在设置中添加了这一行,如果您没有添加它,默认情况下身份验证将尝试在auth_user中搜索用户,而不是在您的自定义用户中搜索:

AUTH_USER_MODEL = 'base.user_auth'(将base更改为您的应用程序的名称)。

其次,我不得不将模型更改为继承自AbstractUser,而不是model.Model(我还添加了用户名字段和unicode函数,尽管我认为它们并不是非常必要的):

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

对于视图和序列化器,我没有做任何更改。

英文:

I made it work , here is what I changed .
first I added this line to the settings if you didn't add it authenticate by defaul will try to search for the user in auth_user and not in your custom user :

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

Second thing I had to change model by inherits from AbstractUser and not model.Model (and I also add username field and unicod function even tho i don't thing they are so much necessary ):

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.

For view and serializer didn't change anything.

huangapple
  • 本文由 发表于 2023年5月25日 19:39:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76331862.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定