djangodjango-rest-frameworkdjango-rest-framework-simplejwtdjoser

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


I'm using Django==4.0.3 ,djangorestframework==3.13.1 and djangorestframework-simplejwt==5.1.0 and djoser==2.1.0 I have used djoser to authenticate, and all works fine.

When the user is not active yet, the response is same as when user enter wrong password

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

I need to customize this response. I have checked this message inside a dictionary in the class TokenObtainSerializer

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

have tried to override this class with no success.

Any ideas?


Solution

  • Try to override the validate() method of TokenObtainSerializer as follows:

    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)
    

    Now update your serializer class to use the custom serializer as:

    class MyTokenObtainPairSerializer(CustomTokenObtainPairSerailizer):
        pass