在 Django 中使用上下文处理器访问视图中的全局变量 [英] Accessing global variable in view using context processor in Django

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

问题描述

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

def 标题(请求):返回 {'titles': 'mytitle'}

我可以在模板中以 {{ titles }} 的形式访问这个变量.

但是我怎样才能在视图中这样做呢?

def myview(request):打印请求.titles

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

<小时>

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

提前致谢.

解决方案

上下文处理器在任何情况下都不是全局变量.它们只是在启动 RequestContext 时运行的函数,将项目添加到该上下文.因此,它们仅在您有 RequestContext 的任何地方可用,即在模板中.

您的示例并没有很好地说明您要访问哪些变量.如果只是你想在任何地方使用的一些常量,一个好的方法是在中央的某个地方定义它们,比如在 settings.py 中,然后在你需要的任何地方导入该模块 - 加上使用上下文处理器将它们添加到上下文中.

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