python - Django 中间件 process_template_response 方法未被调用

标签 python django django-templates

我有以下中间件类:

class CommonContextMiddleware:
    def process_template_response(self, request, response):
        # Get the context and top videos
        context = response.context_data

        ...

        # Add most_recent and most_viewed to the context...
        context['most_recent'] = top_videos['most_recent'][:3]
        context['most_viewed'] = top_videos['most_viewed'][:3]

        # ...then continue rendering
        return response

但是,无论我在函数中放入什么,它都不会被调用。我认为生成的每个模板响应都会调用此方法,我错了吗?

提前致谢。

最佳答案

我假设当您谈论“模板响应”时,您实际上返回的是 TemplateResponse从你的 Django View 来看?

这并不是做此类事情的最佳地点。如果您只想将变量添加到每个模板上下文中,那么最好的位置是在 context processor 中。 .

关于python - Django 中间件 process_template_response 方法未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6318090/

相关文章:

python - Rolling_mean 在特定时间段内使用 Pandas

Python2/Windows7 : Opening filename that contains a german Umlaut

django - “dict”对象没有 friend 属性

python - 如何使用 Django 的 ORM 进行过滤聚合

python - Django 模板 : key, 值在 for 循环中不可能

python - 网页抓取 : scrape multiple webs by Python

python - 在名称约定更改的循环中生成变量名称

django - 在is_valid()之后将Django形式设置为错误

javascript - 我们如何使 htmx 响应触发表单重置?

python - Django 模板中带空格的字典键