Django Rest framwork validation: Mark field as error

456 views Asked by At

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!

1

There are 1 answers

1
Kevin Brown-Silva On BEST ANSWER

When you are creating the ValidationError, you can pass in a dictionary instead of a string. The dictionary expects that the key is the field name, and the value is the error string.

def validate(self, attrs):
    """
    Check that the start is before the stop.
    """
    if attrs['start'] > attrs['finish']:
        raise serializers.ValidationError({"finish": "finish must occur after start"})
    return attrs

This should produce output along the lines of:

{"start": ["finish must occur after start"], 
 "finish": ["finish must occur after start"]}

Which sounds like what you are looking for.