Raise 404 on incorrect lookup type in URL, not 500. Closes #890.

This commit is contained in:
Tom Christie 2013-05-28 11:57:11 +01:00
parent 7123f0b1e6
commit 138f0cacdb
2 changed files with 22 additions and 1 deletions

View File

@ -6,7 +6,7 @@ from __future__ import unicode_literals
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from django.core.paginator import Paginator, InvalidPage
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.shortcuts import get_object_or_404 as _get_object_or_404
from django.utils.translation import ugettext as _
from rest_framework import views, mixins, exceptions
from rest_framework.request import clone_request
@ -14,6 +14,17 @@ from rest_framework.settings import api_settings
import warnings
def get_object_or_404(queryset, **filter_kwargs):
"""
Same as Django's standard shortcut, but make sure to raise 404
if the filter_kwargs don't match the required types.
"""
try:
return _get_object_or_404(queryset, **filter_kwargs)
except (TypeError, ValueError):
raise Http404
class GenericAPIView(views.APIView):
"""
Base class for all other generic views.

View File

@ -279,6 +279,16 @@ class TestInstanceView(TestCase):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, expected)
def test_get_instance_view_incorrect_arg(self):
"""
GET requests with an incorrect pk type, should raise 404, not 500.
Regression test for #890.
"""
request = factory.get('/a')
with self.assertNumQueries(0):
response = self.view(request, pk='a').render()
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_put_cannot_set_id(self):
"""
PUT requests to create a new object should not be able to set the id.