Skip to content

Commit 651319e

Browse files
committed
Fix nested validation error being rendered incorrectly.
Previously an extra list wrapped nested validation errors raised from serializer's validate() methods. That was inconsistent with the format of validation errors raised by validate_<fieldname> methods. i.e. these two resulted in *different* behaviour: def validate_foo(self): raise ValidationError(['bar']) def validate(self): raise ValidationError({'foo': ['bar']})
1 parent 37f7b76 commit 651319e

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

rest_framework/serializers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,7 @@ def get_validation_error_detail(exc):
306306
# If errors may be a dict we use the standard {key: list of values}.
307307
# Here we ensure that all the values are *lists* of errors.
308308
return {
309-
key: value if isinstance(value, list) else [value]
309+
key: value if isinstance(value, (list, dict)) else [value]
310310
for key, value in exc.detail.items()
311311
}
312312
elif isinstance(exc.detail, list):

tests/test_validation.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,24 @@ class Meta:
4949
fields = ('renamed',)
5050

5151

52+
class TestNestedValidationError(TestCase):
53+
def test_nested_validation_error_detail(self):
54+
"""
55+
Ensure nested validation error detail is rendered correctly.
56+
"""
57+
e = serializers.ValidationError({
58+
'nested': {
59+
'field': ['error'],
60+
}
61+
})
62+
63+
self.assertEqual(serializers.get_validation_error_detail(e), {
64+
'nested': {
65+
'field': ['error'],
66+
}
67+
})
68+
69+
5270
class TestPreSaveValidationExclusionsSerializer(TestCase):
5371
def test_renamed_fields_are_model_validated(self):
5472
"""

0 commit comments

Comments
 (0)