Add ValidationError to except in get_object_or_404 for django 1.11

This commit is contained in:
Nabil Jamaleddine 2017-05-05 21:17:12 -04:00
parent 69b0ac52c2
commit cdb8a3c3c8
2 changed files with 21 additions and 2 deletions

View File

@ -3,6 +3,7 @@ Generic views that provide commonly needed behaviour.
""" """
from __future__ import unicode_literals from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.db.models.query import QuerySet from django.db.models.query import QuerySet
from django.http import Http404 from django.http import Http404
from django.shortcuts import get_object_or_404 as _get_object_or_404 from django.shortcuts import get_object_or_404 as _get_object_or_404
@ -18,7 +19,7 @@ def get_object_or_404(queryset, *filter_args, **filter_kwargs):
""" """
try: try:
return _get_object_or_404(queryset, *filter_args, **filter_kwargs) return _get_object_or_404(queryset, *filter_args, **filter_kwargs)
except (TypeError, ValueError): except (TypeError, ValueError, ValidationError):
raise Http404 raise Http404

View File

@ -2,6 +2,7 @@ from __future__ import unicode_literals
import pytest import pytest
from django.db import models from django.db import models
from django.http import Http404
from django.shortcuts import get_object_or_404 from django.shortcuts import get_object_or_404
from django.test import TestCase from django.test import TestCase
from django.utils import six from django.utils import six
@ -10,7 +11,8 @@ from rest_framework import generics, renderers, serializers, status
from rest_framework.response import Response from rest_framework.response import Response
from rest_framework.test import APIRequestFactory from rest_framework.test import APIRequestFactory
from tests.models import ( from tests.models import (
BasicModel, ForeignKeySource, ForeignKeyTarget, RESTFrameworkModel BasicModel, ForeignKeySource, ForeignKeyTarget, RESTFrameworkModel,
UUIDForeignKeyTarget
) )
factory = APIRequestFactory() factory = APIRequestFactory()
@ -647,3 +649,19 @@ class ApiViewsTests(TestCase):
view.delete('test request', 'test arg', test_kwarg='test') view.delete('test request', 'test arg', test_kwarg='test')
assert view.called is True assert view.called is True
assert view.call_args == data assert view.call_args == data
class GetObjectOr404Tests(TestCase):
def setUp(self):
super(GetObjectOr404Tests, self).setUp()
self.uuid_object = UUIDForeignKeyTarget.objects.create(name='bar')
def test_get_object_or_404_with_valid_uuid(self):
obj = generics.get_object_or_404(
UUIDForeignKeyTarget, pk=self.uuid_object.pk
)
assert obj == self.uuid_object
def test_get_object_or_404_with_invalid_string_for_uuid(self):
with pytest.raises(Http404):
generics.get_object_or_404(UUIDForeignKeyTarget, pk='not-a-uuid')