CategoryView未显示

时间:2018-01-12 12:50:07

标签: python django

未显示CategoryView。我在views.py中写道,如

class CategoryView(ListView):
    model = Category

    def get_object(self):
        category_name = self.kwargs['category']
        return Category.objects.get(name=category_name)

class DetailView(generic.DetailView):
    model = POST
    template_name = 'detail.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comment_form'] = CommentCreateForm()
        return context

in detail.html

<div>
    <p>{{ object.text }}</p>
</div>

          <div>
            <a href="#" class="list-group-item active">
              Category
            </a>
                   <div>
                         {% for category in get_object.comment_set.all %}
                            <a href="{% url 'category' category.name %}">
                            {{ category.name }}
                            </a>
                         {% endfor %}
                   </div>
          </div>
在urls.py中

urlpatterns = [
        path('top/', views.top, name='top'),
        path('detail/<int:pk>/', views.DetailView.as_view(), name='detail'),
        path('category/<str:category>/',views.CategoryView.as_view(), name='category'),
    ]

但是现在在detail.html中没有显示类别数据。我真的不明白为什么会发生这种情况。我想我可以在模板中使用get_object.comment_set.all来获取数据,但这是错误的。我该怎么解决这个问题?我的代码有问题吗? 通过阅读评论,我重写了

class CategoryView(ListView):
    model = Category

    def get_object(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['category'] = Category
        return context

但没有显示类别。我想在分类模型中显示所有类别。 此外,我写了

class DetailView(generic.DetailView):
    model = POST
    template_name = 'detail.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comment_form'] = CommentCreateForm()
        context['category'] = Category
        return context

但同样的事情发生了。

1 个答案:

答案 0 :(得分:0)

在详情视图的get_context_data方法中,您可以将类别列表添加到上下文中:

class DetailView(generic.DetailView):
    ...
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        ...
        context['categories'] = Category.objects.all()
        return context

然后在详细视图的模板中,您可以循环浏览categories

<ul>
  {% for category in categories %}
    <li>{{ category.name }}</li>
  {% endfor %}
</ul>