Django-如何从中间件修改模板上下文 [英] Django - How to modify template context from middleware

查看:171
本文介绍了Django-如何从中间件修改模板上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个Django中间件,该中间件管理带有会话的购物车".我能够像这样成功地修改会话数据:

I am creating a Django middleware that manages a 'shopping cart' with sessions. I was able to successfully modify the session data like so:

class ShoppingCartMiddleware:

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Ensure shopping cart exists
        if request.session.get('shopping_cart') is None:
            request.session['shopping_cart'] = {'items': []}
        return self.get_response(request)

我现在需要修改模板上下文,以便我的模板可以访问有关购物车的某些信息(物品数量等).我查看了上下文处理器,但是上下文处理器无法查看会话,甚至无法查看当前上下文.

I now need to modify the template context so that my templates can have access to certain information about the shopping cart (number of items, etc). I looked at context processors, but context processors are not able to view the session or even the current context.

我尝试使用process_template_response钩子,如下所示:

I tried using the process_template_response hook like so:

def process_template_response(self, request, response):
    response.context_data['cart_num_items'] = len(request.session['shopping_cart']['items'])
    return response

但是很显然,当执行钩子时,response.context_dataNone.

but apparently when the hook is executed, response.context_data is None.

有人知道如何使用中间件编辑模板上下文吗?任何帮助将不胜感激.

Does anyone know how to edit the template context with middleware? Any help would be appreciated.

推荐答案

由于可以访问request对象本身,因此无需修改上下文.只需添加一个新属性:

You don't have to modify the context as you have access to the request object itself. Just add a new attribute:

class ShoppingCartMiddleware:
    ...
    def __call__(self, request):
        shopping_cart = {'product': 'Blah', 'id': 123}
        request.shopping_cart = shopping_cart
        ...

然后在您的模板中使用它

then use it in your template

{{ request.shopping_cart.product }}

这篇关于Django-如何从中间件修改模板上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆