如何将通用字典数据传递到django中的每个页面 [英] How to pass common dictionary data to every page in django

查看:279
本文介绍了如何将通用字典数据传递到django中的每个页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个共同的数据(登录的用户的消息号)显示在每个页面上。我可以简单地传递给模板作为

  dict = {'messagenumber':5} 
return render_to_response('template。 html',dict,context_instance = RequestContext(request))

但是,如果我有这个dict数据传递到非常页面。有没有更简单的方法来将通用数据传递给每一页?



谢谢

解决方案>

这让我感觉到这是多么的普遍。你想使用上下文处理器我的朋友!



很容易创建,如下所示:

  def messagenumber_processor请求):
return {'messagenumber':5}

由于messagenumber是一个动态变量基于用户,您可以从 request.user 中提取数据库中的数据,因为您可以完全访问请求在每个上下文处理器中。



然后,添加到您的 TEMPLATE_CONTEXT_PROCESSORS ,您全部设置:-)您可以执行任何形式的数据库操作或上下文处理器中的其他逻辑,还可以尝试一下!


I have a common data {the logged-in user's message number) to display on every page. I can simply pass to template as

dict={'messagenumber':5}
return render_to_response('template.html',dict,context_instance=RequestContext(request))

But it looks tedious if i have this dict data pass to very page. Is there an easier way to pass common data to every page?

Thanks

解决方案

It blows me away how common this is. You want to use context processors my friend!

Very easy to create, like so:

def messagenumber_processor(request):
   return {'messagenumber': 5}

Since messagenumber is a dynamic variable based on the User, you could pull data from the database by fetching from request.user as you have full access to request within each context processor.

Then, add that to your TEMPLATE_CONTEXT_PROCESSORS within settings.py and you're all set :-) You can do any form of database operation or other logic within the context processor as well, try it out!

这篇关于如何将通用字典数据传递到django中的每个页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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