django中间件设置用户特殊全局变量
如果每个网页都有用户新消息通知(新消息计数,如消息(1)),我如何将变量“{new_message_count:1}”传递给每个视图 我想使用中间件:
class page_variable():
def process_request(self, request):
# put the variable to the request or response so can used in template variable
return None
模板看起来像:
<a href="/message/">new <em>({{ new_message_count }})</em></a>
if every web page has a user new message notice(new message count, like message(1)), how can i pass variable '{ new_message_count: 1}' to every view
i want to using middleware:
class page_variable():
def process_request(self, request):
# put the variable to the request or response so can used in template variable
return None
and template look like:
<a href="/message/">new <em>({{ new_message_count }})</em></a>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
已经有一个内置的 消息传递框架 可以为您处理所有这些事情。
但是,假设您确实想推出自己的产品,则无法将内容从中间件传递到上下文中。您可以将其附加到
request
对象,然后可以在视图或模板中使用该对象,或者添加一个上下文处理器,该处理器从请求中获取变量并将其添加到上下文。There's already a built-in messaging framework that handles all of this for you.
However, assuming you really want to roll your own, you can't pass things into the context from middleware. You can attach it to the
request
object, which you can then use in your view or template, or add a context processor which takes the variable from the request and adds it into the context.在 django 的开发版本中,您可以在渲染之前从中间件编辑模板上下文:
在 Django 1.2 中,您可以创建自定义上下文处理器:
并在设置中注册它
In the development version of django, you can edit template context from a middleware before rendering:
In Django 1.2 you can create a custom context processor:
and register it in settings