有时需要在公共模板部分访问特定的变量,目前有两种办法:
方法1:将变量使用部分修改为使用Ajax方式获取和调用; 方法2:使用django的context_processors机制
步骤1:定义一个python文件命名为context_processors.py可以放在你的app中。
from django.conf import settings # import the settings file
def config(request):
return {'DEBUG': settings.DEBUG}
步骤2:在settings.py中加入下面内容:
TEMPLATES[0]["OPTIONS"]["context_processors"].append("c4store.context_processors.config")
步骤3:在views.py的render或者render_to_response中加context_instance=RequestContext(request)参数,或者使用c.update(csrf(request))方法
def index(request):
# 方式一
return render("home/index.html", {}, context_instance=RequestContext(request))
def index(request):
# 方式二
c = {}
c.update(csrf(request))
return render("home/index.html", c)
如果你不想那么麻烦那请再settings.py中加入django.template.context_processors.csrf配置
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
...
'django.template.context_processors.csrf',
...
],
},
},
]
步骤4:在模板中使用变量
{% if DEBUG %}
<div id="showconsole" style="position:absolute; z-index: 999999; background-color: #fff;"></div>
{% endif %}
