python - 如何使帖子类别列表在 django 的所有页面中可见
问题描述
我正在尝试使类别名称在每个页面中都可见。所以为此我将类别模型传递给每个视图。但这里它只在 category_view.html 页面中可见。当我在导航栏中列出类别名称时,我想让它随处可见。
到目前为止我做了这个
模板/导航栏.html
<nav class="nav d-flex justify-content-between">
{%for name in category_name %}
{% for lst in post %}
<a class="p-2 text-muted" href="{% url 'posts:categoryview' slug=name.slug %}">{{name}}</a>
{% endfor %}
{% endfor %}
</nav>
视图.py
from django.shortcuts import render, get_object_or_404,render_to_response
from .models import Post, Category
# Create your views here.
def posts_list(request):
query_list = Post.objects.all()
category_name = Category.objects.all()
context = {
"title" : "Latest Post",
"query_list": query_list,
"category_name": category_name
}
return render(request, "post_list.html", context)
def view_category(request, slug):
category = get_object_or_404(Category, slug=slug)
category_name = Category.objects.all()
return render_to_response('category_view.html', {
'category': category,
'post': Post.objects.filter(category=category).values(),
'category_name': category_name
})
网址.py
urlpatterns = [
path("", posts_list, name="list"),
path("<slug>", view_category, name="categoryview"),
]
解决方案
推荐阅读
- mysql - 根据另一列的值将值插入新表中的列
- javascript - 导航栏在滚动后不显示导航链接
- python - Python 脚本和 Apache Airflow Scheduler 之间是否可以直接通信?
- sql - T-SQL 意外结果中的变量连接
- android - 从小部件打开透明活动时,如何防止活动从后台显示?
- javascript - React js - 如何从 HTML 表中选择所有行 ID
- unity3d - 这里封装有什么用
- node.js - 无法查询类型 Query 上的字段注册
- java - Spring bean() 切入点不适用于 OR 语句
- c++ - 格式化 setw() 函数相当于 1 \t 制表符