使用Django中的上下文处理器查看全局变量 [英] Accessing global variable in view using context processor in Django

查看:296
本文介绍了使用Django中的上下文处理器查看全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个上下文处理器:

  def title(request):
return {'titles' 'mytitle'}

我可以在模板中访问这个变量作为 {{titles



但是,如何在视图中执行此操作?

  def myview(request):
print request.titles

似乎不起作用 - 'WSGIRequest'对象没有属性'title'






或者也可能有更好的方法(比上下文处理器)在两个视图和模板中都可以访问全局变量?



提前感谢。

解决方案

上下文处理器不是全局变量。它们只是在启动RequestContext时运行的函数,它将项目添加到该上下文。所以它们只能在你有一个RequestContext的任何地方,也就是在一个模板中。



你的例子并不是很好的了解你正在寻找哪些变量访问。如果只是一些你想要使用的常量,一个很好的方法是将它们定义在中央位置,比如说settings.py,然后在需要的地方导入该模块,再加上下文处理器将它们添加到上下文中。 p>

Assuming I have a context processor:

def title(request):
   return {'titles': 'mytitle'}

I can access this variable in template as {{ titles }}.

But how can I do so in a view?

def myview(request):
    print request.titles

doesn't seem to work - 'WSGIRequest' object has no attribute 'titles'


Or maybe there is a better approach (than context processors) to have global variables accessible in both views and templates?

Thanks in advance.

解决方案

Context processors aren't in any way global variables. They are simply functions that are run when a RequestContext is initiated, which add items to that context. So they're only available wherever you have a RequestContext, ie in a template.

Your examples don't really give a good idea of what variables you're looking to access. If it's just some constants you want to use everywhere, a good way is to define them somewhere central, say in settings.py, and import that module wherever you need it - plus use a context processor to add them to the context.

这篇关于使用Django中的上下文处理器查看全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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