From 651319e2da0cd46319a622220a864c1da63b8001 Mon Sep 17 00:00:00 2001 From: Craig de Stigter Date: Wed, 6 Jan 2016 16:04:23 +1300 Subject: [PATCH] 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_ methods. i.e. these two resulted in *different* behaviour: def validate_foo(self): raise ValidationError(['bar']) def validate(self): raise ValidationError({'foo': ['bar']}) --- rest_framework/serializers.py | 2 +- tests/test_validation.py | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 99d36a8a5..ada1c1620 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -306,7 +306,7 @@ def get_validation_error_detail(exc): # If errors may be a dict we use the standard {key: list of values}. # Here we ensure that all the values are *lists* of errors. return { - key: value if isinstance(value, list) else [value] + key: value if isinstance(value, (list, dict)) else [value] for key, value in exc.detail.items() } elif isinstance(exc.detail, list): diff --git a/tests/test_validation.py b/tests/test_validation.py index 855ff20e0..b6f274219 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -49,6 +49,24 @@ class ShouldValidateModelSerializer(serializers.ModelSerializer): fields = ('renamed',) +class TestNestedValidationError(TestCase): + def test_nested_validation_error_detail(self): + """ + Ensure nested validation error detail is rendered correctly. + """ + e = serializers.ValidationError({ + 'nested': { + 'field': ['error'], + } + }) + + self.assertEqual(serializers.get_validation_error_detail(e), { + 'nested': { + 'field': ['error'], + } + }) + + class TestPreSaveValidationExclusionsSerializer(TestCase): def test_renamed_fields_are_model_validated(self): """