Fix nested validation error being rendered incorrectly. by craigds · Pull Request #3801 · encode/django-rest-framework (original) (raw)
I went all-out and tried three different approaches to raising the same error. In the process I found my description of the problem was slightly incorrect. The issue occurs when raising a nested ValidationError
from an outer serializer. It's not actually about validate
vs validate_foo
.
This code shows all three cases:
from rest_framework import serializers
validation error is created by the outer serializer's validate() method
class Nested1(serializers.Serializer): foo = serializers.CharField()
class Outer1(serializers.Serializer): nested = Nested1()
def validate(self, attrs):
raise serializers.ValidationError({'nested': {'foo': ['bar']}})
error is created by the inner serializer's validate() method
class Nested2(serializers.Serializer): foo = serializers.CharField()
def validate(self, attrs):
raise serializers.ValidationError({'foo': ['bar']})
class Outer2(serializers.Serializer): nested = Nested2()
error is created by the inner serializer's validate_foo() method
class Nested3(serializers.Serializer): foo = serializers.CharField()
def validate_foo(self, value):
raise serializers.ValidationError(['bar'])
class Outer3(serializers.Serializer): nested = Nested3()
o1 = Outer1(data={'nested': {'foo': 'thing'}}) o1.is_valid() o2 = Outer2(data={'nested': {'foo': 'thing'}}) o2.is_valid() o3 = Outer3(data={'nested': {'foo': 'thing'}}) o3.is_valid()
print o1.errors print o2.errors print o3.errors
This results in:
{'nested': [{'foo': ['bar']}]} {'nested': {'foo': ['bar']}} {'nested': OrderedDict([('foo', ['bar'])])}
Case 1 is the weird one; cases 2 and 3 are the same as each other (OrderedDict notwithstanding)
My fix changes case 1, so the new output is:
{'nested': {'foo': ['bar']}} {'nested': {'foo': ['bar']}} {'nested': OrderedDict([('foo', ['bar'])])}
in which all three are equivalent.