使用 Django 中的上下文处理器访问视图中的全局变量
假设我有一个上下文处理器:
def title(request):
return {'titles': 'mytitle'}
我可以在模板中以 {{ titles }}
的形式访问此变量。
但我怎样才能在视图中做到这一点呢?
def myview(request):
print request.titles
似乎不起作用 - 'WSGIRequest' 对象没有属性 'titles'
或者也许有更好的方法(比上下文处理器)可以在视图和模板中访问全局变量?
提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将上下文处理器方法路径 (folder.context_processor.application_context) 添加到 TEMPLATE_CONTEXT_PROCESSORS。
就我而言, application_context 是我在文件 context_processor.py 中定义的方法
,方法“application_context”返回{'titles':'mytitle'},
如果你想在视图中使用“title”作为全局变量
以这种方式使用它唯一的优点是“相同的变量'titles'对于模板是可见的,而且在你看来”
Add your context processor method path (folder.context_processor.application_context) to TEMPLATE_CONTEXT_PROCESSORS.
in my case application_context is the method which i defined inside file context_processor.py
and method "application_context" returns {'titles': 'mytitle'}
if you want to use "title" as global variable in views use it in this way
The only advantage is "Same variable 'titles' will be visible for templates and also in your views"
上下文处理器无论如何都不是全局变量。它们只是在启动 RequestContext 时运行的函数,将项目添加到该上下文中。因此,它们仅在您有 RequestContext 的地方可用,即在模板中。
您的示例并不能很好地了解您要访问的变量。如果您只是想在任何地方使用一些常量,一个好方法是在中心位置定义它们,例如在 settings.py 中,然后在需要的地方导入该模块 - 加上使用上下文处理器将它们添加到上下文中。
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.
如果您需要视图中的数据,那么将中间件与上下文处理器结合使用会更干净:
request.x
(示例)。现在您可以直接在视图中访问它。TEMPLATE_CONTEXT_PROCESSORS
中启用django.core.context_processors.request
以便从模板访问 request.x。请参阅我的相关问题: Django:如何提供上下文所有视图(不是模板)?
If you need the data in your views, it's cleaner to use Middleware in conjunction with a Context Processor:
request.x
(example). Now you can access this in your views directly.django.core.context_processors.request
in yourTEMPLATE_CONTEXT_PROCESSORS
to have request.x accessible from your templates.See my related question: Django: How to provide context to all views (not templates)?