Skip to content

Instantly share code, notes, and snippets.

@chriskief
Created October 24, 2013 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriskief/7131033 to your computer and use it in GitHub Desktop.
Save chriskief/7131033 to your computer and use it in GitHub Desktop.
from django.shortcuts import _get_queryset
from app.exceptions.custom import NotFound
def get_object_or_template(klass, template, *args, **kwargs):
# replacement for django.shortcuts.get_object_or_404()
# allows a template to be supplied instead of a 404
"""
Uses get() to return an object, or raises a Http404 exception if the object
does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the get() query.
Note: Like with get(), an MultipleObjectsReturned will be raised if more than one
object is found.
"""
queryset = _get_queryset(klass)
try:
return queryset.get(*args, **kwargs)
except queryset.model.DoesNotExist:
raise NotFound(template)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment