I started using django-rest-framework for my application and I have a question regarding the serializer validaton. In the docs I found this example for object validation:
from rest_framework import serializers
class EventSerializer(serializers.Serializer):
description = serializers.CharField(max_length=100)
start = serializers.DateTimeField()
finish = serializers.DateTimeField()
def validate(self, attrs):
"""
Check that the start is before the stop.
"""
if attrs['start'] > attrs['finish']:
raise serializers.ValidationError("finish must occur after start")
return attrs
This returns the following:
{"non_field_errors": ["finish must occur after start"]}
My question is, how can I find out which fields are responsible for the failed validation? In this case attrs['start'] and attrs['finish']. In the end I want something like this:
{"non_field_errors": ["finish must occur after start"],
"start": ["finish must occur after start"],
"finish": ["finish must occur after start"]}
So that I can mark the responsible form fields. I hope the question is clear. Thanks!
When you are creating the
ValidationError
, you can pass in a dictionary instead of a string. The dictionary expects that thekey
is the field name, and thevalue
is the error string.This should produce output along the lines of:
Which sounds like what you are looking for.