自定义用户不活动时检索到的默认消息 djangorestframework-simplejwt?

Customize default message djangorestframework-simplejwt retrieved when the user is not active?

我正在使用 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"}

我需要自定义此回复。我已经在 class TokenObtainSerializer

的字典中检查了这条消息
   default_error_messages = {
    'no_active_account': _('No active account found with the given credentials')
}

已尝试覆盖此 class 但没有成功。

有什么想法吗?

尝试重写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 以将自定义序列化程序用作:

class MyTokenObtainPairSerializer(CustomTokenObtainPairSerailizer):
    pass