您可以通过两种方式将标题值传递给 HTML 模板:
1) 覆盖视图 get_context 方法,从数据库中查询值并像我的示例一样传递(python 3.6):
class MyView(TemplateView):
template_name = '...'
....
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
title = ... # query from database here
data['title'] = title
return data
2) 1 方法的缺点 - 您应该在每个视图中手动实现查询或实现 BaseView 并继承项目中的所有其他视图。你也可以实现上下文处理器,见下面的例子:
# file <project_root>/<app_dir>/context_processor.py
def app_context(request):
# query from database
title = ... # query from database here
return dict(site_title=title)
......................
# file <settings_dir>/settings.py
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',
'<app_package>/context_processor.app_context'
],
},
},
]
该方法的优点 - 变量 site_title 可在上下文处理器 django 应用程序的所有模板中访问
在此处查看官方文档编写您自己的上下文处理器 https://docs.djangoproject.com/en/2.0/ref/templates/api/