问题描述
假设我有一个上下文处理器:
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中的上下文处理器查看全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!