首页 > 解决方案 > 如何使帖子类别列表在 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"),

]

标签: pythondjango

解决方案


推荐阅读