django - 在每个视图的页脚中列出类别
问题描述
我希望在包含页脚的任何模板的页脚中都有我的类别。我有一个Category
模型,目前我这样做的方式是通过我的上下文导入所有类别对象。显然这是相当多余的。
视图.py
def homepage_view(request):
context = {
"categories": Category.objects.all(),
}
return render(request=request,
template_name='main/index.html', context=context)
解决方案
两种可能的解决方案:
1.使用上下文处理器
我认为这将是您最直接的解决方案。这将包括所有请求的上下文对象中可用的类别列表。您只需要在应用设置中添加上下文处理器:
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'myapp.context_processors.include_categories',
],
然后定义该上下文处理器,以便它返回您的类别:
def include_categories(request):
return {'categories': Category.objects.all()}
2. 使用基于类的视图
而不是基于函数的,并创建一个包含上下文中的类别的 mixin。它看起来像:
class IncludeCategoriesMixin(object):
"""
A mixin to add the categories to the view context
"""
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["categories"]: Category.objects.all()
return context
然后,在任何想要包含类别的基于类的视图中,您只需在视图定义中包含 mixin 类:
class MyView(TemplateView, IncludeCategoriesMixin):
...
首先查看文档以了解有关这两种方法的更多信息,但我认为这是您可以用来解决问题的最简单的解决方案。