我正在写博客 - 它有顶部栏菜单,其中包含Categories
个对象。问题是此博客中的每个视图都必须返回context
Categories.objects.all()
。有没有更好的方法来解决这个问题(将相同的查询集添加到每个视图的上下文)?我的代码:
models.py
class Category(models.Model):
name = models.CharField(max_length=60)
slug = models.SlugField(unique=True, blank=True, null=True)
base.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Blog</title>
</head>
<body>
{% block menu %}
<div id="menu">
{% for item in categories %}
<a href="{% url 'category_detail' item.slug %}">
<div class="category">{{ item.name }}</div>
</a>
{% endfor %}
</div>
{% endblock %}
{% block content %}
<!-- I want extend only that block in every view -->
{% endblock %}
</body>
</html>
答案 0 :(得分:3)
您可以通过上下文处理器发送它。只需在settings.py
旁边的根项目中添加一个文件,将其命名为context_processor.py
,然后在内部编写function
,其中request
为参数,必须返回字典强>
from your_app.models import Category
def global_context(request):
cateogries = Category.objects.all()
context = {'categories':categories,}
return context
然后你从settings.py
调用它TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
# codes,
'OPTIONS':{
'context_processors':[
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages', 'django.contrib.messages.context_processors.messages',
# Insert your TEMPLATE_CONTEXT_PROCESSORS here
#'project_name.file_name.function_name',
'project_name.context_processors.global_context',
],
}
},
]
答案 1 :(得分:1)
通过继承%-7
ContextMixin
现在,在您需要类别的每个视图中都会继承from django.views.generic.base import ContextMixin
class CategoryMixin(ContextMixin):
"""
A mixin class that adds categories to all the views that use it.
"""
def get_context_data(self, **kwargs):
ctx = super(CategoryMixin, self).get_context_data(**kwargs)
ctx['categories'] = Categories.objects.all()
return ctx
CategoryMixin