Skip to content

Handle tuples same as lists in ValidationError detail context #7647

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions rest_framework/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def _get_error_details(data, default_code=None):
Descend into a nested data structure, forcing any
lazy translation strings or strings into `ErrorDetail`.
"""
if isinstance(data, list):
if isinstance(data, (list, tuple)):
ret = [
_get_error_details(item, default_code) for item in data
]
Expand Down Expand Up @@ -150,7 +150,9 @@ def __init__(self, detail=None, code=None):

# For validation failures, we may collect many errors together,
# so the details should always be coerced to a list if not already.
if not isinstance(detail, dict) and not isinstance(detail, list):
if isinstance(detail, tuple):
detail = list(detail)
elif not isinstance(detail, dict) and not isinstance(detail, list):
detail = [detail]

self.detail = _get_error_details(detail, code)
Expand Down
10 changes: 10 additions & 0 deletions tests/test_validation_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from rest_framework import serializers, status
from rest_framework.decorators import api_view
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework.settings import api_settings
from rest_framework.test import APIRequestFactory
Expand Down Expand Up @@ -99,3 +100,12 @@ def test_function_based_view_exception_handler(self):
response = view(request)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.data == self.expected_response_data


class TestValidationErrorConvertsTuplesToLists(TestCase):
def test_validation_error_details(self):
error = ValidationError(detail=('message1', 'message2'))
assert isinstance(error.detail, list)
assert len(error.detail) == 2
assert str(error.detail[0]) == 'message1'
assert str(error.detail[1]) == 'message2'