【发布时间】:2020-08-06 07:38:43
【问题描述】:
我必须在每个视图中使用上下文更新方法,以便显示来自我的 sidebar.html 模板的数据,这些数据我包含在其他模板中作为我的导航的一部分。还有另一种方法可以包含来自我的 sidebar.html 其他模板的数据吗?我将不得不为很多模板执行此操作,而且似乎不是正确的方法。
blog/views.py
class BlogPostDetailView(DetailView):
model = BlogPost
context_object_name = "post"
template_name = "blog/single.html"
def get_context_data(self, **kwargs):
context = super(BlogPostDetailView, self).get_context_data(**kwargs)
context.update(
{
"categories": Category.objects.all().annotate(
post_count=Count("categories")
)
},
)
return context
核心/views.py
class HomeView(ListView):
model = BlogPost
context_object_name = "posts"
template_name = "core/index.html"
paginate_by = 4
ordering = ["-date_posted"]
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
context.update(
{
"categories": Category.objects.all().annotate(
post_count=Count("categories")
)
},
)
return context
core/includes/sidebar.html
...
<div class="sidebar-box ftco-animate">
<h3 class="sidebar-heading">Categories</h3>
<ul class="categories">
{% for category in categories %}
<li><a href="#">{{ category.title }}
<span>({{ category.post_count }})</span></a></li>
{% endfor %}
</ul>
</div>
...
【问题讨论】:
标签: django django-views django-templates