Permalink
Browse files

Fixed #925 -- Added TEMPLATE_CONTEXT_PROCESSORS, which lets you speci…

…fy processesors for DjangoContext. Thanks, Luke Plant

git-svn-id: http://code.djangoproject.com/svn/django/trunk@1773 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
1 parent 2d8dfb0 commit d096ac005448343f628d002b134d461cd5801b6d adrian committed Dec 24, 2005
@@ -100,6 +100,15 @@
# 'django.core.template.loaders.eggs.load_template_source',
)
+# List of processors used by DjangoContext to populate the context.
+# Each one should be a callable that takes the request object as its
+# only parameter and returns a dictionary to add to the context.
+TEMPLATE_CONTEXT_PROCESSORS = (
+ 'django.core.context_processors.auth',
+ 'django.core.context_processors.debug',
+ 'django.core.context_processors.i18n',
+)
+
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
View
@@ -2,11 +2,34 @@
# of MVC. In other words, these functions/classes introduce controlled coupling
# for convenience's sake.
-from django.core.exceptions import Http404, ObjectDoesNotExist
+from django.core.exceptions import Http404, ImproperlyConfigured, ObjectDoesNotExist
from django.core.template import Context, loader
-from django.conf.settings import DEBUG, INTERNAL_IPS
+from django.conf.settings import TEMPLATE_CONTEXT_PROCESSORS
from django.utils.httpwrappers import HttpResponse
+_standard_context_processors = None
+
+# This is a function rather than module-level procedural code because we only
+# want it to execute if somebody uses DjangoContext.
+def get_standard_processors():
+ global _standard_context_processors
+ if _standard_context_processors is None:
+ processors = []
+ for path in TEMPLATE_CONTEXT_PROCESSORS:
+ i = path.rfind('.')
+ module, attr = path[:i], path[i+1:]
+ try:
+ mod = __import__(module, '', '', [attr])
+ except ImportError, e:
+ raise ImproperlyConfigured, 'Error importing request processor module %s: "%s"' % (module, e)
+ try:
+ func = getattr(mod, attr)
+ except AttributeError:
+ raise ImproperlyConfigured, 'Module "%s" does not define a "%s" callable request processor' % (module, attr)
+ processors.append(func)
+ _standard_context_processors = tuple(processors)
+ return _standard_context_processors
+
def render_to_response(*args, **kwargs):
return HttpResponse(loader.render_to_string(*args, **kwargs))
load_and_render = render_to_response # For backwards compatibility.
@@ -25,24 +48,19 @@ def get_list_or_404(mod, **kwargs):
class DjangoContext(Context):
"""
- This subclass of template.Context automatically populates 'user' and
- 'messages' in the context.
+ This subclass of template.Context automatically populates itself using
+ the processors defined in TEMPLATE_CONTEXT_PROCESSORS.
+ Additional processors can be specified as a list of callables
+ using the "processors" keyword argument.
"""
- def __init__(self, request, dict=None):
+ def __init__(self, request, dict=None, processors=None):
Context.__init__(self, dict)
- self['user'] = request.user
- self['messages'] = request.user.get_and_delete_messages()
- self['perms'] = PermWrapper(request.user)
- from django.conf import settings
- self['LANGUAGES'] = settings.LANGUAGES
- if hasattr(request, 'LANGUAGE_CODE'):
- self['LANGUAGE_CODE'] = request.LANGUAGE_CODE
+ if processors is None:
+ processors = ()
else:
- self['LANGUAGE_CODE'] = settings.LANGUAGE_CODE
- if DEBUG and request.META.get('REMOTE_ADDR') in INTERNAL_IPS:
- self['debug'] = True
- from django.core import db
- self['sql_queries'] = db.db.queries
+ processors = tuple(processors)
+ for processor in get_standard_processors() + processors:
+ self.update(processor(request))
# PermWrapper and PermLookupDict proxy the permissions system into objects that
# the template system can understand.
@@ -3,14 +3,14 @@
from django.core.template import loader
from django.core import formfields, meta
from django.views.auth.login import redirect_to_login
-from django.core.extensions import DjangoContext as Context
+from django.core.extensions import DjangoContext
from django.core.paginator import ObjectPaginator, InvalidPage
from django.utils.httpwrappers import HttpResponse, HttpResponseRedirect
from django.core.exceptions import Http404, ObjectDoesNotExist, ImproperlyConfigured
def create_object(request, app_label, module_name, template_name=None,
- template_loader=loader, extra_context={},
- post_save_redirect=None, login_required=False, follow=None):
+ template_loader=loader, extra_context={}, post_save_redirect=None,
+ login_required=False, follow=None, context_processors=None):
"""
Generic object-creation function.
@@ -60,9 +60,9 @@ def create_object(request, app_label, module_name, template_name=None,
if not template_name:
template_name = "%s/%s_form" % (app_label, module_name)
t = template_loader.get_template(template_name)
- c = Context(request, {
- 'form' : form,
- })
+ c = DjangoContext(request, {
+ 'form': form,
+ }, context_processors)
for key, value in extra_context.items():
if callable(value):
c[key] = value()
@@ -71,9 +71,9 @@ def create_object(request, app_label, module_name, template_name=None,
return HttpResponse(t.render(c))
def update_object(request, app_label, module_name, object_id=None, slug=None,
- slug_field=None, template_name=None, template_loader=loader,
- extra_lookup_kwargs={}, extra_context={}, post_save_redirect=None,
- login_required=False, follow=None):
+ slug_field=None, template_name=None, template_loader=loader,
+ extra_lookup_kwargs={}, extra_context={}, post_save_redirect=None,
+ login_required=False, follow=None, context_processors=None):
"""
Generic object-update function.
@@ -131,10 +131,10 @@ def update_object(request, app_label, module_name, object_id=None, slug=None,
if not template_name:
template_name = "%s/%s_form" % (app_label, module_name)
t = template_loader.get_template(template_name)
- c = Context(request, {
- 'form' : form,
- 'object' : object,
- })
+ c = DjangoContext(request, {
+ 'form': form,
+ 'object': object,
+ }, context_processors)
for key, value in extra_context.items():
if callable(value):
c[key] = value()
@@ -145,9 +145,9 @@ def update_object(request, app_label, module_name, object_id=None, slug=None,
return response
def delete_object(request, app_label, module_name, post_delete_redirect,
- object_id=None, slug=None, slug_field=None, template_name=None,
- template_loader=loader, extra_lookup_kwargs={},
- extra_context={}, login_required=False):
+ object_id=None, slug=None, slug_field=None, template_name=None,
+ template_loader=loader, extra_lookup_kwargs={}, extra_context={},
+ login_required=False, context_processors=None):
"""
Generic object-delete function.
@@ -188,9 +188,9 @@ def delete_object(request, app_label, module_name, post_delete_redirect,
if not template_name:
template_name = "%s/%s_confirm_delete" % (app_label, module_name)
t = template_loader.get_template(template_name)
- c = Context(request, {
- 'object' : object,
- })
+ c = DjangoContext(request, {
+ 'object': object,
+ }, context_processors)
for key, value in extra_context.items():
if callable(value):
c[key] = value()
@@ -199,4 +199,3 @@ def delete_object(request, app_label, module_name, post_delete_redirect,
response = HttpResponse(t.render(c))
populate_xheaders(request, response, app_label, module_name, getattr(object, object._meta.pk.name))
return response
-
@@ -1,14 +1,14 @@
from django.core.template import loader
from django.core.exceptions import Http404, ObjectDoesNotExist
-from django.core.extensions import DjangoContext as Context
+from django.core.extensions import DjangoContext
from django.core.xheaders import populate_xheaders
from django.models import get_module
from django.utils.httpwrappers import HttpResponse
import datetime, time
def archive_index(request, app_label, module_name, date_field, num_latest=15,
- template_name=None, template_loader=loader,
- extra_lookup_kwargs={}, extra_context={}, allow_empty=False):
+ template_name=None, template_loader=loader, extra_lookup_kwargs={},
+ extra_context={}, allow_empty=False, context_processors=None):
"""
Generic top-level archive of date-based objects.
@@ -38,10 +38,10 @@ def archive_index(request, app_label, module_name, date_field, num_latest=15,
if not template_name:
template_name = "%s/%s_archive" % (app_label, module_name)
t = template_loader.get_template(template_name)
- c = Context(request, {
+ c = DjangoContext(request, {
'date_list' : date_list,
'latest' : latest,
- })
+ }, context_processors)
for key, value in extra_context.items():
if callable(value):
c[key] = value()
@@ -50,8 +50,8 @@ def archive_index(request, app_label, module_name, date_field, num_latest=15,
return HttpResponse(t.render(c))
def archive_year(request, year, app_label, module_name, date_field,
- template_name=None, template_loader=loader,
- extra_lookup_kwargs={}, extra_context={}):
+ template_name=None, template_loader=loader, extra_lookup_kwargs={},
+ extra_context={}, context_processors=None):
"""
Generic yearly archive view.
@@ -75,10 +75,10 @@ def archive_year(request, year, app_label, module_name, date_field,
if not template_name:
template_name = "%s/%s_archive_year" % (app_label, module_name)
t = template_loader.get_template(template_name)
- c = Context(request, {
+ c = DjangoContext(request, {
'date_list': date_list,
'year': year,
- })
+ }, context_processors)
for key, value in extra_context.items():
if callable(value):
c[key] = value()
@@ -87,8 +87,8 @@ def archive_year(request, year, app_label, module_name, date_field,
return HttpResponse(t.render(c))
def archive_month(request, year, month, app_label, module_name, date_field,
- month_format='%b', template_name=None, template_loader=loader,
- extra_lookup_kwargs={}, extra_context={}):
+ month_format='%b', template_name=None, template_loader=loader,
+ extra_lookup_kwargs={}, extra_context={}, context_processors=None):
"""
Generic monthly archive view.
@@ -123,10 +123,10 @@ def archive_month(request, year, month, app_label, module_name, date_field,
if not template_name:
template_name = "%s/%s_archive_month" % (app_label, module_name)
t = template_loader.get_template(template_name)
- c = Context(request, {
+ c = DjangoContext(request, {
'object_list': object_list,
'month': date,
- })
+ }, context_processors)
for key, value in extra_context.items():
if callable(value):
c[key] = value()
@@ -135,9 +135,9 @@ def archive_month(request, year, month, app_label, module_name, date_field,
return HttpResponse(t.render(c))
def archive_day(request, year, month, day, app_label, module_name, date_field,
- month_format='%b', day_format='%d', template_name=None,
- template_loader=loader, extra_lookup_kwargs={},
- extra_context={}, allow_empty=False):
+ month_format='%b', day_format='%d', template_name=None,
+ template_loader=loader, extra_lookup_kwargs={}, extra_context={},
+ allow_empty=False, context_processors=None):
"""
Generic daily archive view.
@@ -172,12 +172,12 @@ def archive_day(request, year, month, day, app_label, module_name, date_field,
if not template_name:
template_name = "%s/%s_archive_day" % (app_label, module_name)
t = template_loader.get_template(template_name)
- c = Context(request, {
+ c = DjangoContext(request, {
'object_list': object_list,
'day': date,
'previous_day': date - datetime.timedelta(days=1),
'next_day': (date < datetime.date.today()) and (date + datetime.timedelta(days=1)) or None,
- })
+ }, context_processors)
for key, value in extra_context.items():
if callable(value):
c[key] = value()
@@ -198,10 +198,10 @@ def archive_today(request, **kwargs):
return archive_day(request, **kwargs)
def object_detail(request, year, month, day, app_label, module_name, date_field,
- month_format='%b', day_format='%d', object_id=None, slug=None,
- slug_field=None, template_name=None, template_name_field=None,
- template_loader=loader, extra_lookup_kwargs={},
- extra_context={}):
+ month_format='%b', day_format='%d', object_id=None, slug=None,
+ slug_field=None, template_name=None, template_name_field=None,
+ template_loader=loader, extra_lookup_kwargs={}, extra_context={},
+ context_processors=None):
"""
Generic detail view from year/month/day/slug or year/month/day/id structure.
@@ -241,9 +241,9 @@ def object_detail(request, year, month, day, app_label, module_name, date_field,
t = template_loader.select_template(template_name_list)
else:
t = template_loader.get_template(template_name)
- c = Context(request, {
+ c = DjangoContext(request, {
'object': object,
- })
+ }, context_processors)
for key, value in extra_context.items():
if callable(value):
c[key] = value()
@@ -2,13 +2,13 @@
from django.core.template import loader
from django.utils.httpwrappers import HttpResponse
from django.core.xheaders import populate_xheaders
-from django.core.extensions import DjangoContext as Context
+from django.core.extensions import DjangoContext
from django.core.paginator import ObjectPaginator, InvalidPage
from django.core.exceptions import Http404, ObjectDoesNotExist
def object_list(request, app_label, module_name, paginate_by=None, allow_empty=False,
- template_name=None, template_loader=loader,
- extra_lookup_kwargs={}, extra_context={}):
+ template_name=None, template_loader=loader, extra_lookup_kwargs={},
+ extra_context={}, context_processors=None):
"""
Generic list of objects.
@@ -48,7 +48,7 @@ def object_list(request, app_label, module_name, paginate_by=None, allow_empty=F
else:
raise Http404
page = int(page)
- c = Context(request, {
+ c = DjangoContext(request, {
'object_list': object_list,
'is_paginated': paginator.pages > 1,
'results_per_page': paginate_by,
@@ -59,13 +59,13 @@ def object_list(request, app_label, module_name, paginate_by=None, allow_empty=F
'previous': page - 1,
'pages': paginator.pages,
'hits' : paginator.hits,
- })
+ }, context_processors)
else:
object_list = mod.get_list(**lookup_kwargs)
- c = Context(request, {
+ c = DjangoContext(request, {
'object_list': object_list,
'is_paginated': False
- })
+ }, context_processors)
if len(object_list) == 0 and not allow_empty:
raise Http404
for key, value in extra_context.items():
@@ -79,9 +79,9 @@ def object_list(request, app_label, module_name, paginate_by=None, allow_empty=F
return HttpResponse(t.render(c))
def object_detail(request, app_label, module_name, object_id=None, slug=None,
- slug_field=None, template_name=None, template_name_field=None,
- template_loader=loader, extra_lookup_kwargs={},
- extra_context={}):
+ slug_field=None, template_name=None, template_name_field=None,
+ template_loader=loader, extra_lookup_kwargs={}, extra_context={},
+ context_processors=None):
"""
Generic list of objects.
@@ -110,9 +110,9 @@ def object_detail(request, app_label, module_name, object_id=None, slug=None,
t = template_loader.select_template(template_name_list)
else:
t = template_loader.get_template(template_name)
- c = Context(request, {
+ c = DjangoContext(request, {
'object': object,
- })
+ }, context_processors)
for key, value in extra_context.items():
if callable(value):
c[key] = value()
Oops, something went wrong.

0 comments on commit d096ac0

Please sign in to comment.