Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

django

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?

like image 993
John Lehmann Avatar asked Mar 13 '23 09:03

John Lehmann


1 Answers

Use Middleware...

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

        request.extra_model = self.get_model(request.user)
like image 159
mwjackson Avatar answered Mar 24 '23 15:03

mwjackson