我正在尝试在每个页面中显示类别名称。因此,我将类别模型传递给每个视图。但是,此处仅在category_view.html页面中可见。 我要在导航栏中列出类别名称时,使其在任何地方都可见。
到目前为止,我做到了
templates / navbar.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>
views.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
})
urls.py
urlpatterns = [
path("", posts_list, name="list"),
path("<slug>", view_category, name="categoryview"),
]