pythondjangodjango-rest-frameworkjwtdjango-rest-framework-jwt

JWT: How do I implement my custom error message on password or username is wrong Django REST


I want to implement my own custome error message when user types wrong password in Django Rest JWT authentiction as of now default error message is

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

I have inherited Token Obtain serializer as

class TokenPairSerializer(TokenObtainSerializer):
    default_error_messages = {
        'login_error': _('Username or Password does not matched .')
    }

    @classmethod
    def get_token(cls, user):
        return RefreshToken.for_user(user)

    @classmethod
    def get_user_type(cls, user):
        if user.is_superuser:
            return 'super_user'
        elif user.is_student:
            return 'student_user'
        elif user.is_teacher:
            return 'teacher_user'

    def validate(self, attrs):
        data = super().validate(attrs)
        self.validate_user()
        refresh = self.get_token(self.user)

I don't know where can I need to overrid error message to get response as this

    'login_error': _('Username or Password does not matched .')

any help will be helpful.


Solution

  • If you only need to change the default error message, override the TokenObtainSerializer default_error_message dictionary, and customize the no_active_account key.

    Source code: here

    to

    class CustomTokenObtainSerializer(TokenObtainPairSerializer):
        default_error_messages = {
            'no_active_account': 'Username or Password does not matched.'
        }