John Lehmann
John Lehmann

Reputation: 8225

Django: How to provide context to all views (not templates)?

I want to provide some context to all my function-based views (FBV) similar to the way TEMPLATE_CONTEXT_PROCESSORS (CP) provides context to all of one's templates. The latter doesn't work for me because I need that context prior to rendering the templates.

In particular, on my site I have a function which takes a request and returns the model for the Category of item in focus. My CP provides this for all templates, but I find myself making the same call from my FBV's and would like to remove this redundancy.

This question is similar but it presupposes the approach of accessing the output of the CP from the views. This seems hacky, and I'm not sure it's the best approach.

What's the Django way to do this?

Upvotes: 5

Views: 2369

Answers (2)

Raphael Fernandes
Raphael Fernandes

Reputation: 861

Based on mwjackson 's answer and on docs, for Django 1.11, I think the middleware should be:

# middleware/my_middleware.py
class MyModelMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        # TODO - your processing here
        request.extra_model = result_from_processing
        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response

In settings.py, add the path to your Middleware on MIDDLEWARE = () . Following the tips from this site, I had created a folder inside my app called middleware and added a new file, say my_middleware.py, with a class called, say, MyModelMiddleware. So, the path that I had added to MIDDLEWARE was my_app.middleware.my_middleware.MyModelMiddleware.

# settings.py
MIDDLEWARE = (
    ...
    'my_app.middleware.my_middleware.MyModelMiddleware',
)

Upvotes: 1

mwjackson
mwjackson

Reputation: 5451

Use Middleware...

class MyModelMiddleware(object):
    def process_request(self, request):

        request.extra_model = self.get_model(request.user)

Upvotes: 6

Related Questions