2005-09-24 05:40:04 +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.
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-09-22 01:24:33 +08:00
|
|
|
from django.core import template_loader
|
2005-09-24 05:40:04 +08:00
|
|
|
from django.core.exceptions import Http404, ObjectDoesNotExist
|
2005-07-13 09:25:57 +08:00
|
|
|
from django.core.template import Context
|
|
|
|
from django.conf.settings import DEBUG, INTERNAL_IPS
|
2005-09-22 01:24:33 +08:00
|
|
|
from django.utils.httpwrappers import HttpResponse
|
|
|
|
|
2005-09-22 22:57:05 +08:00
|
|
|
def render_to_response(*args, **kwargs):
|
|
|
|
return HttpResponse(template_loader.render_to_string(*args, **kwargs))
|
|
|
|
load_and_render = render_to_response # For backwards compatibility.
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-09-24 05:40:04 +08:00
|
|
|
def get_object_or_404(mod, **kwargs):
|
|
|
|
try:
|
|
|
|
return mod.get_object(**kwargs)
|
|
|
|
except ObjectDoesNotExist:
|
|
|
|
raise Http404
|
|
|
|
|
|
|
|
def get_list_or_404(mod, **kwargs):
|
|
|
|
obj_list = mod.get_list(**kwargs)
|
|
|
|
if not obj_list:
|
|
|
|
raise Http404
|
|
|
|
return obj_list
|
|
|
|
|
2005-07-16 01:09:01 +08:00
|
|
|
class DjangoContext(Context):
|
|
|
|
"""
|
|
|
|
This subclass of template.Context automatically populates 'user' and
|
|
|
|
'messages' in the context.
|
|
|
|
"""
|
2005-09-18 07:08:24 +08:00
|
|
|
def __init__(self, request, dict=None):
|
2005-07-13 09:25:57 +08:00
|
|
|
Context.__init__(self, dict)
|
|
|
|
self['user'] = request.user
|
|
|
|
self['messages'] = request.user.get_and_delete_messages()
|
|
|
|
self['perms'] = PermWrapper(request.user)
|
2005-07-21 22:01:17 +08:00
|
|
|
if DEBUG and request.META.get('REMOTE_ADDR') in INTERNAL_IPS:
|
2005-07-13 09:25:57 +08:00
|
|
|
self['debug'] = True
|
|
|
|
from django.core import db
|
|
|
|
self['sql_queries'] = db.db.queries
|
|
|
|
|
|
|
|
# PermWrapper and PermLookupDict proxy the permissions system into objects that
|
|
|
|
# the template system can understand.
|
|
|
|
|
|
|
|
class PermLookupDict:
|
|
|
|
def __init__(self, user, module_name):
|
|
|
|
self.user, self.module_name = user, module_name
|
|
|
|
def __repr__(self):
|
2005-07-14 11:17:09 +08:00
|
|
|
return str(self.user.get_permission_list())
|
2005-07-13 09:25:57 +08:00
|
|
|
def __getitem__(self, perm_name):
|
|
|
|
return self.user.has_perm("%s.%s" % (self.module_name, perm_name))
|
|
|
|
def __nonzero__(self):
|
|
|
|
return self.user.has_module_perms(self.module_name)
|
|
|
|
|
|
|
|
class PermWrapper:
|
|
|
|
def __init__(self, user):
|
|
|
|
self.user = user
|
|
|
|
def __getitem__(self, module_name):
|
|
|
|
return PermLookupDict(self.user, module_name)
|