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

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

问题描述

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

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))

但是如果我将这个 dict 数据传递到非常页面,它看起来很乏味.有没有更简单的方法可以将通用数据传递到每个页面?

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?

谢谢

推荐答案

这让我感到震惊.你想使用上下文处理器我的朋友!

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}

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

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.

然后,将其添加到您的TEMPLATE_CONTEXT_PROCESSORS 在 settings.py 中,您就全部设置好了 :-) 您也可以在上下文处理器中执行任何形式的数据库操作或其他逻辑,试试吧!

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天全站免登陆