From bfe9448358d0c8250a6a2f6efd9a3d85a68568d1 Mon Sep 17 00:00:00 2001 From: Anton Chasnyk Date: Wed, 11 Aug 2021 16:58:02 +0300 Subject: [PATCH] processing only str (#8077) --- rest_framework/exceptions.py | 11 +++++++---- tests/test_validation_error.py | 8 ++++---- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/rest_framework/exceptions.py b/rest_framework/exceptions.py index 0870baa54..593b329f3 100644 --- a/rest_framework/exceptions.py +++ b/rest_framework/exceptions.py @@ -153,10 +153,13 @@ class ValidationError(APIException): # For validation failures, we may collect many errors together, # so the details should always be coerced to a list if not already. - if isinstance(detail, tuple) or isinstance(detail, list): - detail = [msg % params for msg in detail] - elif not isinstance(detail, dict): - detail = [detail % params] + # For str or list of str add params + if isinstance(detail, str): + detail = [detail % params] + elif isinstance(detail, list) or isinstance(detail, tuple): + detail = [msg % params if isinstance(msg, str) else msg for msg in detail] + elif not isinstance(detail, dict) and not isinstance(detail, list): + detail = [detail] self.detail = _get_error_details(detail, code) diff --git a/tests/test_validation_error.py b/tests/test_validation_error.py index 0453e362d..32b1ee247 100644 --- a/tests/test_validation_error.py +++ b/tests/test_validation_error.py @@ -110,21 +110,21 @@ class TestValidationErrorConvertsTuplesToLists(TestCase): assert str(error.detail[0]) == 'message1' assert str(error.detail[1]) == 'message2' + class TestvalidationErrorWithDjangoStyle(TestCase): def test_validation_error_details(self): error = ValidationError('Invalid value: %(value)s', params={'value': '42'}) - s = str(error.detail) assert str(error.detail[0]) == 'Invalid value: 42' - + def test_validation_error_details_tuple(self): - error = ValidationError(detail=('Invalid value: %(value1)s', 'Invalid value: %(value2)s'), params={'value1': '42', 'value2':'43'}) + error = ValidationError(detail=('Invalid value: %(value1)s', 'Invalid value: %(value2)s'), params={'value1': '42', 'value2': '43'}) assert isinstance(error.detail, list) assert len(error.detail) == 2 assert str(error.detail[0]) == 'Invalid value: 42' assert str(error.detail[1]) == 'Invalid value: 43' def test_validation_error_details_list(self): - error = ValidationError(detail=['Invalid value: %(value1)s', 'Invalid value: %(value2)s'], params={'value1': '42', 'value2':'43'}) + error = ValidationError(detail=['Invalid value: %(value1)s', 'Invalid value: %(value2)s'], params={'value1': '42', 'value2': '43'}) assert isinstance(error.detail, list) assert len(error.detail) == 2 assert str(error.detail[0]) == 'Invalid value: 42'