自定义默认消息djangorestframework-simplejwt检索时,用户不活跃?

6za6bjd0  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(192)

我使用Django==4.0.3,djangorestframework==3.13.1和djangorestframework-simplejwt==5.1.0和djoser==2.1.0我使用djoser进行身份验证,一切正常。
当用户尚未激活时,响应与用户输入错误密码时相同

{"detail":"No active account found with the given credentials"}

我需要定制此响应。我已经在类TokenObtainSerializer的字典中检查了此消息

default_error_messages = {
    'no_active_account': _('No active account found with the given credentials')
}

已尝试重写此类,但未成功。
有什么想法吗

hrysbysz

hrysbysz1#

尝试覆盖TokenObtainSerializer的validate()方法,如下所示:

serializers.py

class CustomTokenObtainPairSerializer(TokenObtainSerailizer):
    def validate():
        ...
        authenticate_kwargs = {
            self.username_field: attrs[self.username_field],
            'password': attrs['password'],
        }
        try:
            authenticate_kwargs['request'] = self.context['request']
        except KeyError:
            pass
        self.user = authenticate(**authenticate_kwargs)
        print(self.user)
        if self.user is None or not self.user.is_active:
            self.error_messages['no_active_account'] = _(
                'No active account found with the given credentials') # --> Change this error message for what you want to replace this with.
            raise exceptions.AuthenticationFailed(
                self.error_messages['no_active_account'],
                'no_active_account',
            )
        return super().validate(attrs)

现在更新您的序列化器类,以使用自定义序列化器作为:

class MyTokenObtainPairSerializer(CustomTokenObtainPairSerailizer):
    pass

相关问题