我们知道,前端页面的数据是从数据库获取的,如果有多个html页面的数据是相同的话,在views.py文件里面定义的多个函数中就需要多次从数据库中获取相同的数据,如果每个view都需要返回同样的数据,那么就需要考虑上下文管理器
1.首先,定义一个上下文管理器的py文件,content_processors.py,在这个文件中统一获取需要用到的数据
代码如下:
from . import models
def process_category(request):
categories = models.Category.objects.all()
return {‘categories‘:categories}
def process_title(request):
web_site = models.WebSite.objects.all().first()
return {‘web_site‘:web_site}
2.django的setting中配置上下文管理器
TEMPLATES = [
{
‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘,
‘DIRS‘: [ os.path.join(BASE_DIR,‘templates‘) ],#指的django寻找html模板的目录
‘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‘,
‘user.content_processors.process_category‘,
‘user.content_processors.process_title‘,
],
},
},
]
3.那么在views.py中的函数中就不需要在从数据库中查找并返回上下文管理器中所返回的数据,直接在前端页面应用就可以了
原文:https://www.cnblogs.com/liulilitoday/p/13580754.html