2
This module collects helper functions and classes that "span" multiple levels
3
of MVC. In other words, these functions/classes introduce controlled coupling
4
for convenience's sake.
7
from django.template import loader
8
from django.http import HttpResponse, Http404
9
from django.db.models.manager import Manager
10
from django.db.models.query import QuerySet
12
def render_to_response(*args, **kwargs):
14
Returns a HttpResponse whose content is filled with the result of calling
15
django.template.loader.render_to_string() with the passed arguments.
17
httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}
18
return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
20
def _get_queryset(klass):
22
Returns a QuerySet from a Model, Manager, or QuerySet. Created to make
23
get_object_or_404 and get_list_or_404 more DRY.
25
if isinstance(klass, QuerySet):
27
elif isinstance(klass, Manager):
30
manager = klass._default_manager
33
def get_object_or_404(klass, *args, **kwargs):
35
Uses get() to return an object, or raises a Http404 exception if the object
38
klass may be a Model, Manager, or QuerySet object. All other passed
39
arguments and keyword arguments are used in the get() query.
41
Note: Like with get(), an MultipleObjectsReturned will be raised if more than one
44
queryset = _get_queryset(klass)
46
return queryset.get(*args, **kwargs)
47
except queryset.model.DoesNotExist:
48
raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
50
def get_list_or_404(klass, *args, **kwargs):
52
Uses filter() to return a list of objects, or raise a Http404 exception if
55
klass may be a Model, Manager, or QuerySet object. All other passed
56
arguments and keyword arguments are used in the filter() query.
58
queryset = _get_queryset(klass)
59
obj_list = list(queryset.filter(*args, **kwargs))
61
raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)