Home > front end >  How to customise the default error message for empty username on login
How to customise the default error message for empty username on login

Time:06-16

login credentials :

{
    "account_id":"",
    "password":"abdu@123"
}

response :

{
  "account_id": [
    "This field may not be blank."
  ]
}

This error comes from rest_framework.fields.CharField. I tried to override it by doing :

class MyField(CharField):
    default_error_messages = {
        'invalid': _('Not a valid string.'),
        'blank': _('This field may not be blank changed......'),
        'max_length': _('Ensure this field has no more than {max_length} characters.'),
        'min_length': _('Ensure this field has at least {min_length} characters.'),
    }

This doesn't change the error message. My Serializer :

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    
    @classmethod
    def get_token(cls, user):
        ...
        return token

    def validate(self, attrs):
       ... 

        
        data = super(MyTokenObtainPairSerializer, self).validate(attrs)
        data.update({"user_id": self.user.account_seq})
        data.update({"account_id": self.user.account_id})
        data.update({"is_migrated": int(self.user.is_migrated)})
        data.update({"role": self.user.authority})
        return data

models.py:

class User(AbstractBaseUser):
   ...
    account_id = models.CharField(max_length=255, unique=True)
   ...

CodePudding user response:

I think you don't need to create your own field. You can just add the error_messages attribute like the following.

class User(AbstractBaseUser):
    ...
    account_id = models.CharField(max_length=255, unique=True, error_messages = {
        'blank': '...',
        'null': '...',
        'invalid': '...',
        'max_length': '...'
    })

CodePudding user response:

one way to do so is as follow

class LoginSerializer(serializers.Serializer):
    account_id = serializers.CharField()
    password = serializers.CharField()
.
    def validate(self, attrs):
        errors = dict()
        if attrs['account_id'] == "" or attrs['account_id'] is None:
            errors["account_id"] = "Account ID may not be empty"
            raise serializers.ValidationError(errors)
        return super().validate(attrs)

It will first try to validate with your custom logic and with super() it validate with inbuilt logic. If you catch errors type prior to inbuilt you can provide custom error messages

CodePudding user response:

This worked for me:

I overrode init method of TokenObtainPairSerializer and manually checked if the request is empty and then threw a custom error.

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):

    def __init__(self, *args, **kwargs):
        acc_id = kwargs.get('data').get("account_id")
        password = kwargs.get('data').get("password")
        if not acc_id:
            raise MyCustomExcpetion(
                detail={"error": "account id cannot be empty"}, status_code=status.HTTP_403_FORBIDDEN
            )
        val = super().__init__(self,*args,**kwargs)
        return val

    ...
  • Related