如何在Django中有效地从多个视图中排除类似的上下文



假设我们有两个或多个视图,其中每个视图模板都从base.html扩展而来,并且在base.html文件内部是上下文变量project_namecompany_name:

文件base.html

<!DOCTYPE html>
<html>
<head>
<title>{{ project_name }}</title>
</head>
<body>
{{ company_name }}
{% block content %}{% endblock %}
</body>
</html>

然后,我们必须将上述背景添加到我们的观点中,如下所示:

文件views.py

def view1(request)
context = {
"view1 data": "some data",
"project_name": "Project Name",
"company_name": "Company Name",
}
return render(request, "view1.html", context)

class View2(DetailView):
template_name = "view2.html"
model = SampleModel
def get_context_data(self, **kwargs):
context = super(View2, self).get_context_data(**kwargs)
context["view2 data"] = "sample data"
context["project_name"] = "Project Name"
context["company_name"] = "Company Name"
return context

我们如何编写一个高效的代码,使我们的视图看起来如下,即公共上下文project_namecompany_name在其他地方被分解,但仍将显示在base.html中?

所需视图.py

def view1(request)
context = {
"view1 data": "some data",
}
return render(request, "view1.html", context)

class View2(DetailView):
template_name = "view2.html"
model = SampleModel
def get_context_data(self, **kwargs):
context = super(View2, self).get_context_data(**kwargs)
context["view2 data"] = "sample data"
return context

可以理解的是,基于函数的视图和基于类的视图的功能可能不同,因此每种视图都可能有不同的解决方案。

据我所知,我知道有一些方法可以更有效地实现这一点。但是添加一个上下文处理器对我来说是有效的

因此,以下代码片段将使您了解该过程:

在您的任何应用程序文件夹中创建一个新的Python文件;最好将其命名为"context_processors.py"。在"context_pprocessors.py"文件中,您可以写:

def any_function_name(request):
any_dictionary_name = {
"view1 data": "some data",
"project_name": "Project Name",
"company_name": "Company Name",
}
return any_dictionary_name

(注意:像这样,您甚至可以编写queryset来获取任何数据并使其全局可用(

然后转到主项目的文件settings。py添加上下文处理器的引用:

TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
'DIRS': [],
'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',
'your_app_name.context_processors.any_function_name' #Add the file reference here
],
},
},
]

之后,您可以访问模板中的任何位置的上下文数据,如下所示:

<!DOCTYPE html>
<html>
<head>
<title>{{ project_name }}</title>
</head>
<body>
{{ company_name }}
{% block content %}{% endblock %}
</body>
</html>

最新更新