[Answer]-Django View Preprocessing

1đź‘Ť

âś…

Actually, what you really probably want is middleware, if the setting is going to affect the template that’s chosen in the first place, or substantially affect the response. It is a good deal more flexible than using a template context processor, which is more appropriate if you simply want to add a couple variables to your context.

You create a middleware.py in your app, which might contain something like:

from django.conf import settings

class MyMiddleware(object):
    def process_request(self, request):
        request.my_app_setting = settings.MY_APP_SETTING

Don’t forget to add your class to your MIDDLEWARE_CLASSES setting.

👤acjay

0đź‘Ť

You can use custom template context processors for passing “global” context to your views.

To accomplish this, create a new contextprocessors.py somewhere in your application with code similar to the example below (all it has to do is return a dict). Then add the path to the file with the function in the TEMPLATE_CONTEXT_PROCESSORS tuple in your settings.py (ie: yourapp.contextprocessors.resource_urls).

from django.conf import settings

def resource_urls(request):
    """Passes global values to templates."""

    return dict(
        TIME_ZONE = settings.TIME_ZONE,
    )

Now you can refer to these keys in your templates as expected: {{ TIME_ZONE }}.

👤garnertb

Leave a comment