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

后端 未结 2 495
太阳男子
太阳男子 2021-01-19 04:32

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 templa

相关标签:
2条回答
  • 2021-01-19 05:08

    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',
    )
    
    0 讨论(0)
  • 2021-01-19 05:28

    Use Middleware...

    class MyModelMiddleware(object):
        def process_request(self, request):
    
            request.extra_model = self.get_model(request.user)
    
    0 讨论(0)
提交回复
热议问题