我有以下中间件类:
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/