Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 815
Michal G Avatar asked Aug 13 '26 11:08

Michal G


1 Answers

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.

like image 189
Peter Sobhi Avatar answered Aug 16 '26 01:08

Peter Sobhi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!