Python – Django rest framework: Overwriting validation error keys

Django rest framework: Overwriting validation error keys… here is a solution to the problem.

Django rest framework: Overwriting validation error keys

There was a problem translating my website into another language.
I want to handle Validation Errors properly and make my front-end friend display them well.

Is there a way to override the key in the DRF response message when a validation error occurs?
What does this mean – I want to change this :

{
    "name": ["This field is required."]
}

Go in:

{
    "username": ["This field is required."]
}

Is there a way to do this without having to write every validator?

Solution

You can change the name field in ModelSerializer to username.

Example:

class CustomSerializer(serializers. ModelSerializer):
    username = serializers. CharField(source='name')

class Meta:
        model = ...
        fields = ('username', ...)

Now in validation errors, it will use key username instead.

Related Problems and Solutions