在Django项目中,方法authenticate返回None

cwdobuhd  于 2023-03-09  发布在  Go
关注(0)|答案(3)|浏览(152)

我有一个问题与authenticate()方法。它总是返回无。我检查了我所有的参数,他们不是空的。在模型中,我有USERNAME_FIELD = 'username',在设置中,我有AUTH_USER_MODEL = 'account.User'。我真的不明白为什么它不工作。
models.py

class UserManager(BaseUserManager):
    def _create(self, username, password):
        if not username:
            raise ValueError('Username cant be empty')
        user = self.model(username=username)
        user.set_password(raw_password=password)
        user.save()
        return user

    def create_user(self, username, password):
        return self._create(username=username, password=password)

class User(AbstractBaseUser):
    id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='id')
    email = models.EmailField()
    username = models.CharField(max_length=25, unique=True)
    is_active = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    education = models.CharField(max_length=100, blank=True)
    date_of_birth = models.DateField(blank=True, null=True)
    name = models.CharField(max_length=25, blank=True)
    last_name = models.CharField(max_length=25, blank=True)

    objects = UserManager()

    USERNAME_FIELD = 'username'

views.py

class UserLoginView(ObtainAuthToken):
    serializer_class = UserLoginSerializer

serializers.py

class UserLoginSerializer(serializers.Serializer):
    username = serializers.CharField(required=True)
    password = serializers.CharField(required=True)

    def validate_username(self, username):
        if not User.objects.filter(username=username).exists():
            raise serializers.ValidationError('User wasn\'t found')
        print(User.objects.get(username=username).password)
        return username

    def validate(self, data):
        # authentications
        request = self.context.get('request')
        username = data.get('username') # test_name
        password = data.get('password') # newpassword11
        if username and password:
            user = authenticate(username=username, password=password, request=request)
            print(user)
            if not user:
                raise serializers.ValidationError('Invalid password')
        else:
            raise serializers.ValidationError('You have to type you\'re mail and password')
        data['user'] = user
        return data
nfs0ujit

nfs0ujit1#

我通过将模型更改为以下内容修复了它:

class User(AbstractBaseUser, PermissionsMixin):
    .....

在将post请求发送到url路由到UserLoginView视图后,post主体处的usernamepassword在响应处获得类似于以下内容的Json:

{"token":"30e0215a5f4cc521203a633452d63995d8f1fa77"}

当使用AbstractBaseUser而不是AbstractUser时,请注意实现Django用户模型的所有要求。
提示:不要忘记正确设置DRF Authentication

wecizke3

wecizke32#

问题出在users字段,称为is_activeDjango只允许在用户处于活动状态时使用login
另外,感谢所有人,他们尽力帮助我们:)

wko9yo5t

wko9yo5t3#

对于任何可能与此错误斗争的人来说,我也面临着同样的问题,并发现我缺少的是在设置文件中声明auth设置。

AUTH_USER_MODEL = "user.User"

AUTHENTICATION_BACKENDS = (
   'django.contrib.auth.backends.ModelBackend',
)

相关问题