2006-05-02 09:31:56 +08: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.
|
|
|
|
|
|
|
|
from django.template import loader
|
|
|
|
from django.http import HttpResponse, Http404
|
2007-01-03 22:16:58 +08:00
|
|
|
from django.db.models.manager import Manager
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
def render_to_response(*args, **kwargs):
|
|
|
|
return HttpResponse(loader.render_to_string(*args, **kwargs))
|
|
|
|
load_and_render = render_to_response # For backwards compatibility.
|
|
|
|
|
2006-05-31 20:34:05 +08:00
|
|
|
def get_object_or_404(klass, *args, **kwargs):
|
2007-01-03 22:16:58 +08:00
|
|
|
if isinstance(klass, Manager):
|
|
|
|
manager = klass
|
|
|
|
klass = manager.model
|
|
|
|
else:
|
|
|
|
manager = klass._default_manager
|
2006-05-02 09:31:56 +08:00
|
|
|
try:
|
2007-01-03 22:16:58 +08:00
|
|
|
return manager.get(*args, **kwargs)
|
2006-05-02 09:31:56 +08:00
|
|
|
except klass.DoesNotExist:
|
|
|
|
raise Http404
|
|
|
|
|
2006-05-31 20:36:01 +08:00
|
|
|
def get_list_or_404(klass, *args, **kwargs):
|
2007-01-03 22:16:58 +08:00
|
|
|
if isinstance(klass, Manager):
|
|
|
|
manager = klass
|
|
|
|
else:
|
|
|
|
manager = klass._default_manager
|
|
|
|
obj_list = list(manager.filter(*args, **kwargs))
|
2006-05-02 09:31:56 +08:00
|
|
|
if not obj_list:
|
|
|
|
raise Http404
|
|
|
|
return obj_list
|