From b3ef67a544e2e50859bfe254e9ebc5892bcdcc90 Mon Sep 17 00:00:00 2001 From: Dan Crosta Date: Thu, 14 Jul 2011 18:43:11 -0400 Subject: [PATCH] get_document_or_404 raises 404 if given an invalid ObjectId (and possibly on other errors, not sure what else raises ValidationError) --- mongoengine/django/shortcuts.py | 3 ++- tests/django_tests.py | 12 +++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/mongoengine/django/shortcuts.py b/mongoengine/django/shortcuts.py index 29bc17a8..59a20741 100644 --- a/mongoengine/django/shortcuts.py +++ b/mongoengine/django/shortcuts.py @@ -1,6 +1,7 @@ from django.http import Http404 from mongoengine.queryset import QuerySet from mongoengine.base import BaseDocument +from mongoengine.base import ValidationError def _get_queryset(cls): """Inspired by django.shortcuts.*""" @@ -25,7 +26,7 @@ def get_document_or_404(cls, *args, **kwargs): queryset = _get_queryset(cls) try: return queryset.get(*args, **kwargs) - except queryset._document.DoesNotExist: + except (queryset._document.DoesNotExist, ValidationError): raise Http404('No %s matches the given query.' % queryset._document._class_name) def get_list_or_404(cls, *args, **kwargs): diff --git a/tests/django_tests.py b/tests/django_tests.py index 930cc113..9c7e3280 100644 --- a/tests/django_tests.py +++ b/tests/django_tests.py @@ -3,7 +3,9 @@ import unittest from mongoengine import * +from mongoengine.django.shortcuts import get_document_or_404 +from django.http import Http404 from django.template import Context, Template from django.conf import settings settings.configure() @@ -56,4 +58,12 @@ class QuerySetTest(unittest.TestCase): self.assertEqual(t.render(Context(d)), 'D-10:C-30:') # Check double rendering doesn't throw an error - self.assertEqual(t.render(Context(d)), 'D-10:C-30:') \ No newline at end of file + self.assertEqual(t.render(Context(d)), 'D-10:C-30:') + + def test_get_document_or_404(self): + p = self.Person(name="G404") + p.save() + + self.assertRaises(Http404, get_document_or_404, self.Person, pk='1234') + self.assertEqual(p, get_document_or_404(self.Person, pk=p.pk)) +