diff --git a/rest_framework/generics.py b/rest_framework/generics.py index 3ee569109..8d0bf284a 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -3,6 +3,7 @@ Generic views that provide commonly needed behaviour. """ from __future__ import unicode_literals +from django.core.exceptions import ValidationError from django.db.models.query import QuerySet from django.http import Http404 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: return _get_object_or_404(queryset, *filter_args, **filter_kwargs) - except (TypeError, ValueError): + except (TypeError, ValueError, ValidationError): raise Http404 diff --git a/tests/test_generics.py b/tests/test_generics.py index f5edb6809..c0ff1c5c4 100644 --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -2,6 +2,7 @@ from __future__ import unicode_literals import pytest from django.db import models +from django.http import Http404 from django.shortcuts import get_object_or_404 from django.test import TestCase 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.test import APIRequestFactory from tests.models import ( - BasicModel, ForeignKeySource, ForeignKeyTarget, RESTFrameworkModel + BasicModel, ForeignKeySource, ForeignKeyTarget, RESTFrameworkModel, + UUIDForeignKeyTarget ) factory = APIRequestFactory() @@ -647,3 +649,19 @@ class ApiViewsTests(TestCase): view.delete('test request', 'test arg', test_kwarg='test') assert view.called is True 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')