App-specific delegation of template context processors

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from django.conf import settings
from django.core.urlresolvers import resolve
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module

def app_delegate(request):
    """
    Leverage the DELEGATED_TEMPLATE_CONTEXT_PROCESSORS setting and url
    application namespaces to delegate template context processors to
    individual apps.
    
    E.g.
    # settings.py
    TEMPLATE_CONTEXT_PROCESSORS = (
        # ...
        'path.to.app_delegate'
    )
    
    DELEGATED_TEMPLATE_CONTEXT_PROCESSORS = {
        'myapp': (
            'myproject.myapp.context_processors.do_something',
        )
    }
    
    # urls.py
    (r'^myapp', include('myproject.myapp.urls', app_name='myapp'))
    
    # The above will execute the "do_something" template context processor for
    # views accessed via urls in the "myapp" application namespace.
    """
    
    app_name = resolve(request.path).app_name
    
    try:
        processors = settings.DELEGATED_TEMPLATE_CONTEXT_PROCESSORS[app_name]
    except KeyError:
        # Not delegating any processors to this app
        return {}
    except AttributeError:
        raise ImproperlyConfigured('DELEGATED_TEMPLATE_CONTEXT_PROCESSORS setting required to use app delegation of template context processors')
    
    context = {}
    
    # Adapted from django.template.context.get_standard_processors
    for path in processors:
        i = path.rfind('.')
        module, attr = path[:i], path[i+1:]
        
        try:
            mod = import_module(module)
        except ImportError as 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))
        
        context.update(func(request))
    
    return context

More like this

  1. Template context processor to make the settings.py values available in templates by tamizhgeek 2 years, 11 months ago
  2. Context processor for django admin app_list by alexander 4 years, 2 months ago
  3. Dynamic Django settings context processor by sciyoshi 5 years, 9 months ago
  4. Expose filtered settings to templates request context by n1k0 3 years, 3 months ago
  5. Output sql_queries in Firebug console when in debug mode by wojas 4 years ago

Comments

(Forgotten your password?)