每个视图的自定义导航栏

Custom navbar for each View

我尝试为每个视图做不同的导航栏。

我可以更好地编码吗,例如使用 href="{% url 'polls:detail' question.id %} ?

现在我创建navbar.html

{% for name, link in navbar.items%}
  <li class="nav-item">
    <a class="nav-link" href={{link}}>{{name}}</a>
  </li>
  {% endfor %}

和观看次数

    class ArticleListView(generic.ListView):
    model = Article
    template_name = 'blog/article_list.html'
    context_object_name = 'articles'
    queryset = Article.objects.all()

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data()
        context['navbar'] = {"Main Page":"/blog/","create":"/blog/create"}
        return context


class ArticleDetailView(generic.DetailView):
    template_name = 'blog/article_detail.html'
    context_object_name = 'article'
    queryset = Article.objects.all()

    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        context['navbar'] = {
            "Main Page": "/blog/",
            "create": "/blog/create",
            "edit": f"/blog/{Article.objects.get(id=self.object.id).id}/update",
            "delete": f"/blog/{Article.objects.get(id=self.object.id).id}/delete",
        }
        return context

假设在urls.py中定义了相应的博客网址 reverse() 方法有助于在视图中生成 url。

 from django.urls import reverse

 context['navbar'] = {
        "Main Page": reverse('blog'),
        "create": reverse('blog_create'),
        "edit": reverse('blog_update', args=[self.object.id]),
        "delete": reverse('blog_delete', args=[self.object.id]),
  }

in模板方式也可以:

 context['navbar'] = {
        "Main Page": 'blog',
        "create": "blog_create",
        "edit": "blog_update",
        "delete": "blog_delete",
  }


{% for name, link in navbar.items%}
  <li class="nav-item">
    <a class="nav-link" href={% url link object.id %}>{{name}}</a>
  </li>
{% endfor %}