0

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

网址.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.titlenotcategory.title如何将此类别列表添加到其他页面,例如索引或文章?这是我完整的 views.py 文件:

视图.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'
4

1 回答 1

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 %}
于 2013-11-30T20:24:54.450 回答