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):
|
2007-06-22 15:15:04 +08:00
|
|
|
return HttpResponse(loader.render_to_string(*args, **kwargs))
|
2006-05-02 09:31:56 +08:00
|
|
|
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:
|
2007-03-21 00:48:41 +08:00
|
|
|
raise Http404('No %s matches the given query.' % klass._meta.object_name)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
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:
|
2007-03-21 00:48:41 +08:00
|
|
|
raise Http404('No %s matches the given query.' % manager.model._meta.object_name)
|
2006-05-02 09:31:56 +08:00
|
|
|
return obj_list
|