Merge pull request #234 from dcrosta/get-or-404
Get or 404 now handles validation errors as well. Thanks @dcrosta
This commit is contained in:
commit
6eb0387a78
@ -1,6 +1,7 @@
|
|||||||
from django.http import Http404
|
from django.http import Http404
|
||||||
from mongoengine.queryset import QuerySet
|
from mongoengine.queryset import QuerySet
|
||||||
from mongoengine.base import BaseDocument
|
from mongoengine.base import BaseDocument
|
||||||
|
from mongoengine.base import ValidationError
|
||||||
|
|
||||||
def _get_queryset(cls):
|
def _get_queryset(cls):
|
||||||
"""Inspired by django.shortcuts.*"""
|
"""Inspired by django.shortcuts.*"""
|
||||||
@ -25,7 +26,7 @@ def get_document_or_404(cls, *args, **kwargs):
|
|||||||
queryset = _get_queryset(cls)
|
queryset = _get_queryset(cls)
|
||||||
try:
|
try:
|
||||||
return queryset.get(*args, **kwargs)
|
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)
|
raise Http404('No %s matches the given query.' % queryset._document._class_name)
|
||||||
|
|
||||||
def get_list_or_404(cls, *args, **kwargs):
|
def get_list_or_404(cls, *args, **kwargs):
|
||||||
|
@ -3,7 +3,9 @@
|
|||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
from mongoengine import *
|
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.template import Context, Template
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
settings.configure()
|
settings.configure()
|
||||||
@ -56,4 +58,12 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
self.assertEqual(t.render(Context(d)), 'D-10:C-30:')
|
self.assertEqual(t.render(Context(d)), 'D-10:C-30:')
|
||||||
|
|
||||||
# Check double rendering doesn't throw an error
|
# 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))
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user