get_document_or_404 raises 404 if given an invalid ObjectId

(and possibly on other errors, not sure what else raises
ValidationError)
This commit is contained in:
Dan Crosta 2011-07-14 18:43:11 -04:00
parent 72995a4b3e
commit b3ef67a544
2 changed files with 13 additions and 2 deletions

View File

@ -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):

View File

@ -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:')
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))