1、譬如设置网站的名称,setting中设置变量:
# setting.py
SITE_NAME = "我的小站"
2、在view中写函数将该变量转换成字典,做返回值
from django.conf import settings
def site_key(request):
# 这里使用的setting中的变量,也可以是在view中设置变量一样的。
return {"SITE_NAME":settings.SITE_NAME}
3、在setting的上下文处理器中增加该函数的处理方法:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'hydros.views.site_key', # view中的site_key函数
],
},
},
]
4、直接在HTML中使用view中返回值的Key即可
<h2>{{ SITE_NAME }}</h2>