J
J
Jekson2020-05-12 13:55:14
Django
Jekson, 2020-05-12 13:55:14

How to change the error output format when validating a field in a serializer?

There is a serializer

class ElementCommonInfoSerializer(serializers.ModelSerializer):

    self_description = serializers.CharField(required=False, allow_null=True,
                                             validators=[RegexValidator(regex=r'^[a-zA-Z0-9,.!? -/*()]*$',
                                                                        message='The system detected that the data is not in English. '
                                                                                'Please correct the error and try again.')]
                                             )
    ....

    class Meta:
        model = Elements
        fields = ('self_description',......)


When an exception occurs, it throws an error like this

{
    "self_description": [
        "The system detected that the data is not in English. Please correct the error and try again."
    ]
}


Those. the key is the field name. I have to give to the front with a different key

{
    "general_errors": [
        "The system detected that the data is not in English. Please correct the error and try again."
    ]
}


How can this be changed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alternativshik, 2020-05-12
@Lepilov

1. rewrite validate from the serializer.
2. in the is_valid() view and return errors in the response in the required form.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question