Michal G
Michal G

Reputation: 45

Django Rest Framework: Overwriting validation error keys

When translating my site to another language a problem occurred. I want to handle Validation Errors properly and allow my front-end friends to display them well.

Is there a way to overwrite keys in response message of DRF when Validation Error happend? What do I mean by that - I want to change this:

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

into:

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

Is there a way to do that without writing each and every one of validators?

Upvotes: 3

Views: 549

Answers (1)

Peter Sobhi
Peter Sobhi

Reputation: 2550

You can change the name field in the ModelSerializer to username.

example:

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

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

Now in validation errors it will have the key username instead.

Upvotes: 3

Related Questions