Eda*_*aor 19 python django constants
我想在Django项目中有一些常量.例如,假设一个常量调用MIN_TIME_TEST.
我希望能够在两个地方访问此常量:从我的Python代码中,以及在任何模板中.
这样做的最佳方法是什么?
编辑: 为了澄清,我知道模板上下文处理器,只是把东西放在settings.py或其他文件中,只是导入.
我的问题是,如何在不违反"不要重复自己"规则的情况下结合这两种方法?根据目前为止的答案,这是我的方法:
我想创建一个名为global_constants.py的文件,它将包含一个常量列表(类似的东西MIN_TIME_TEST = 5).我可以import将此文件放入任何模块中以获取常量.
但是现在,我想创建一个返回所有这些常量的上下文处理器.我怎样才能自动执行此操作,而无需在字典中再次列出它们,例如John Mee的答案?
Joh*_*Mee 17
Luper和Vladimir都是正确的,但你需要两者才能完成你的要求.
虽然参数并不需要是在settings.py,你可以把他们的任何地方,从地方将其导入到你的视图/模型/模块代码.__init__.py如果我不在乎将它们视为与全球相关,我有时会把它们放进去.
像这样的上下文处理器将确保所选变量在模板范围内是全局的
def settings(request):
"""
Put selected settings variables into the default template context
"""
from django.conf import settings
return {
'DOMAIN': settings.DOMAIN,
'GOOGLEMAPS_API_KEY': settings.GOOGLEMAPS_API_KEY,
}
Run Code Online (Sandbox Code Playgroud)但如果你是django的新手,这可能会有点过分.也许你只是问如何将变量放入模板范围......?
from django.conf import settings
...
# do stuff with settings.MIN_TIME_TEST as you wish
render_to_response("the_template.html", {
"MIN_TIME_TEST": settings.MIN_TIME_TEST
}, context_instance=RequestContext(request)
Run Code Online (Sandbox Code Playgroud)
基于其他人的答案,这里有一个简单的方法来实现这个:
在您的设置文件中:
GLOBAL_SETTINGS = {
'MIN_TIME_TEST': 'blah',
'RANDOM_GLOBAL_VAR': 'blah',
}
Run Code Online (Sandbox Code Playgroud)
然后,建立John Mee的上下文处理器:
def settings(request):
"""
Put selected settings variables into the default template context
"""
from django.conf import settings
return settings.GLOBAL_SETTINGS
Run Code Online (Sandbox Code Playgroud)
这将解决DRY问题.
或者,如果您只打算偶尔使用全局设置并希望在视图中调用它们:
def view_func(request):
from django.conf import settings
# function code here
ctx = {} #context variables here
ctx.update(settings.GLOBAL_SETTINGS)
# whatever output you want here
Run Code Online (Sandbox Code Playgroud)