'More descriptive error messages for Django Serializers?

I am deserializing JSON data from file to a model object. I'm using a Django Rest Framework serializer.

The JSON is quite large and I expected some fields that needed tweaking. However, the error messages are not helpful, contrary to those in the docs.

The serializer:

class ChannelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Channel
        fields = '__all__'

The test:

class UnitTests(unittest.TestCase):
    def testDeserializeChannel(self):
        json = Path(Dirs.CHANNELS_METADATA_TEST, 'A SIMULATED REALITY/youtube/A SIMULATED REALITY.json')
        with open(json, 'rb') as file:
            stream = io.BytesIO(file.read())
            parsed_channel = JSONParser().parse(stream)

        serializer = ChannelSerializer(data=parsed_channel, many=True)
        if not serializer.is_valid():  # required for serializer.save() to work
            print(serializer.error_messages, "\n")
            print(serializer.errors)

        channel = serializer.validated_data.save()
        self.assertEqual(channel[0].title, "A SIMULATED REALITY")
        self.assertEqual(channel[0].original_url, "https://www.youtube.com/channel/UCBT3VPJlhJHeIvmDadeZB5w")

The error messages:

{'required': 'This field is required.', 'null': 'This field may not be null.', 'not_a_list': 'Expected a list of items but got type "{input_type}".', 'empty': 'This list may not be empty.', 'max_length': 'Ensure this field has no more than {max_length} elements.', 'min_length': 'Ensure this field has at least {min_length} elements.'} 

{'non_field_errors': [ErrorDetail(string='Expected a list of items but got type "dict".', code='not_a_list')]}

We can see required and null errors but without mentioning of the fields.

I suspect the 'all' bit in the serializer is the cause, contrary to explicitly defined field. Can somebody comfirm? And more importantly, can it be fixed?

Kr,



Solution 1:[1]

You can use DRF's APIException to create your custom exceptions:

from rest_framework.exceptions import APIException

class MyCustomException(APIException):
    status_code = 400
    default_detail = 'This serializer is not valid my friend...'
    default_code = 'bad_request'

Usage:

. . .

if not serializer.is_valid():
    raise MyCustomException()

. . .

Outcome if serializer is not valid:

"detail": {"This serializer is not valid my friend..."}

Like this you can use custom exceptions all around your code. :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Elias Prado