2007-07-22 03:09:24 +00:00
|
|
|
"""
|
|
|
|
This module collects helper functions and classes that "span" multiple levels
|
|
|
|
of MVC. In other words, these functions/classes introduce controlled coupling
|
|
|
|
for convenience's sake.
|
|
|
|
"""
|
2006-05-02 01:31:56 +00:00
|
|
|
|
|
|
|
from django.template import loader
|
|
|
|
from django.http import HttpResponse, Http404
|
2007-01-03 14:16:58 +00:00
|
|
|
from django.db.models.manager import Manager
|
2006-05-02 01:31:56 +00:00
|
|
|
|
|
|
|
def render_to_response(*args, **kwargs):
|
2007-07-22 03:09:24 +00:00
|
|
|
"""
|
|
|
|
Return a HttpResponse whose content is filled with the result of calling
|
|
|
|
django.template.loader.render_to_string() with the passed arguments.
|
|
|
|
"""
|
2007-06-22 07:15:04 +00:00
|
|
|
return HttpResponse(loader.render_to_string(*args, **kwargs))
|
2006-05-02 01:31:56 +00:00
|
|
|
load_and_render = render_to_response # For backwards compatibility.
|
|
|
|
|
2006-05-31 12:34:05 +00:00
|
|
|
def get_object_or_404(klass, *args, **kwargs):
|
2007-07-22 03:09:24 +00:00
|
|
|
"""
|
|
|
|
Use get() to return an object, or raise a Http404 exception if the object
|
|
|
|
does not exist.
|
|
|
|
|
2007-07-22 03:12:50 +00:00
|
|
|
klass may be a Model or Manager object. All other passed
|
2007-07-22 03:09:24 +00:00
|
|
|
arguments and keyword arguments are used in the get() query.
|
|
|
|
|
|
|
|
Note: Like with get(), an AssertionError will be raised if more than one
|
|
|
|
object is found.
|
|
|
|
"""
|
2007-01-03 14:16:58 +00:00
|
|
|
if isinstance(klass, Manager):
|
|
|
|
manager = klass
|
|
|
|
klass = manager.model
|
|
|
|
else:
|
|
|
|
manager = klass._default_manager
|
2006-05-02 01:31:56 +00:00
|
|
|
try:
|
2007-01-03 14:16:58 +00:00
|
|
|
return manager.get(*args, **kwargs)
|
2006-05-02 01:31:56 +00:00
|
|
|
except klass.DoesNotExist:
|
2007-03-20 16:48:41 +00:00
|
|
|
raise Http404('No %s matches the given query.' % klass._meta.object_name)
|
2006-05-02 01:31:56 +00:00
|
|
|
|
2006-05-31 12:36:01 +00:00
|
|
|
def get_list_or_404(klass, *args, **kwargs):
|
2007-07-22 03:09:24 +00:00
|
|
|
"""
|
|
|
|
Use filter() to return a list of objects, or raise a Http404 exception if
|
|
|
|
the list is empty.
|
|
|
|
|
2007-07-22 03:12:50 +00:00
|
|
|
klass may be a Model or Manager object. All other passed
|
2007-07-22 03:09:24 +00:00
|
|
|
arguments and keyword arguments are used in the filter() query.
|
|
|
|
"""
|
2007-01-03 14:16:58 +00:00
|
|
|
if isinstance(klass, Manager):
|
|
|
|
manager = klass
|
|
|
|
else:
|
|
|
|
manager = klass._default_manager
|
|
|
|
obj_list = list(manager.filter(*args, **kwargs))
|
2006-05-02 01:31:56 +00:00
|
|
|
if not obj_list:
|
2007-03-20 16:48:41 +00:00
|
|
|
raise Http404('No %s matches the given query.' % manager.model._meta.object_name)
|
2006-05-02 01:31:56 +00:00
|
|
|
return obj_list
|