From 2aab63d7a56267ffe546c6ee5d18226cbeded997 Mon Sep 17 00:00:00 2001 From: Anton Chasnyk Date: Wed, 11 Aug 2021 10:33:07 +0300 Subject: [PATCH] impruved code ValidationError compatible with Django (#8077) --- rest_framework/exceptions.py | 19 ++++++------------- tests/test_validation_error.py | 9 ++++++++- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/rest_framework/exceptions.py b/rest_framework/exceptions.py index 98ca49e9f..0870baa54 100644 --- a/rest_framework/exceptions.py +++ b/rest_framework/exceptions.py @@ -141,29 +141,22 @@ class ValidationError(APIException): status_code = status.HTTP_400_BAD_REQUEST default_detail = _('Invalid input.') default_code = 'invalid' + default_params = {} def __init__(self, detail=None, code=None, params=None): if detail is None: detail = self.default_detail if code is None: code = self.default_code + if params is None: + params = self.default_params # 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): - detail_list = list() - if params is not None: - for msg in detail: - detail_list.append(msg % params) - detail = detail_list - else: - detail = list(detail) - elif not isinstance(detail, dict) and not isinstance(detail, list): - if params is not None: + if isinstance(detail, tuple) or isinstance(detail, list): + detail = [msg % params for msg in detail] + elif not isinstance(detail, dict): detail = [detail % params] - else: - detail = [detail] - self.detail = _get_error_details(detail, code) diff --git a/tests/test_validation_error.py b/tests/test_validation_error.py index 537506771..0453e362d 100644 --- a/tests/test_validation_error.py +++ b/tests/test_validation_error.py @@ -121,4 +121,11 @@ class TestvalidationErrorWithDjangoStyle(TestCase): 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' \ No newline at end of file + 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'}) + 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'