andersra
andersra

Reputation: 1135

Django View Preprocessing

Just looking for some guidance here on how to implement this concept in "Django fashion".

I am using dbsettings to define site level variables. On each request I want to check one of my site level variables and render a different response based on the value of that variable.

Now I realize I could easily accomplish this just by adding a simple if statement in each of my view functions, but I thought there may be a way I could apply this at a higher level?

Let me know if there is a way to "globalize" this functionality across all requests. Thanks.

Upvotes: 1

Views: 1772

Answers (2)

acjay
acjay

Reputation: 36581

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.

Upvotes: 2

garnertb
garnertb

Reputation: 9594

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 }}.

Upvotes: 0

Related Questions