如何在多个页面中显示通用视图所做的类别列表?

时间:2013-11-30 17:54:17

标签: django django-templates django-generic-views django-1.6

我正在尝试使用Django 1.6构建自己的Blog应用程序。我通过这样的通用视图生成了一个类别列表:

urls.py

url(r'^categories/?$', views.ListView.as_view(model=Category), name='categories'),

category_list.html

   <h3>Categories</h3>
   {% for category in object_list %}
     <ul>
       <li>{{ category.title }}</li>
     </ul>
   {% endfor %}

所有类别现已列在/categories

我的问题是当我将其添加到base.htmlindex.html文件时,输出更改为article.title而非category.title如何将此类别列表添加到其他页面,例如索引还是文章? 这是我完整的views.py文件:

views.py

from django.shortcuts import get_object_or_404, render
from django.views.generic import ListView, DetailView

from blog.models import Article, Category

class IndexView(ListView):
    template_name = 'blog/index.html'
    context_object_name = 'latest_article_list'

    def get_queryset(self):
        return Article.objects.order_by('-pub_date')[:10]

class ArticleView(DetailView):
    model = Article
    template_name = 'blog/article.html'

1 个答案:

答案 0 :(得分:2)

它呈现article.title,因为object_list指向文章视图上下文,您不能将孤立视图包含到另一个视图中。

我认为最干净的方法是为类别上下文创建一个mixin类,并将其添加到每个需要呈现它的视图中。

这样的事情:

class CategoryMixin(object):
    def get_categories(self):
        return Category.objects.all()

    def get_context_data(self, **kwargs):
        context = super(CategoryMixin, self).get_context_data(**kwargs)
        context['categories'] = self.get_categories()
        return context

然后将其添加到视图类:

class IndexView(CategoryMixin, ListView):
    ...

并在每个模板中包含category_list.html,传递上下文变量(这样你就有了孤立的变量名):

{% include "category_list.html" with object_list=categories only %}