如何将ListView类用于两个不同的模板

时间:2014-08-08 16:37:09

标签: python django templates

我在ListView

中有view.py个班级
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic

from entertainment.models import Entertainmentblog

class ListView(generic.ListView):
      template_name = 'entertainment/index.html'
      context_object_name = 'latest_article_list'
      slug = None
      id = None

def get_queryset(self):

      return Entertainmentblog.objects.order_by('-posted')[:25]

class DetailView(generic.DetailView):
      model = Entertainmentblog
      template_name = 'entertainment/article.html'      

我正在使用此视图在index.html中显示文章列表。但是,我想在文章后面article.html中显示相同的文章列表。我使用了块正确但是,它不会显示任何文章,因为在ListView模板名称是index.html。我如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

使用Mixin:

class LatestArticleMixin(object):

    def get_context_data(self, **kwargs):
        context = super(LatestArticleMixin, self).get_context_data(**kwargs)
        try:
            context['latest_article_list'] = Entertainmentblog.objects.order_by('-posted')[:25]
        except:
            pass
        return context

然后重构您的DetailView:

class DetailView(LatestArticleMixin, generic.DetailView):
    model = Entertainmentblog
    template_name = 'entertainment/article.html'

如果有文章,请在模板中填写:

{% if latest_article_list %}
    ....

{% endif %}

答案 1 :(得分:-1)

urls.py中,您可以将template_name设置为ListView url条目路由器的属性。

<强> urls.py

urlpatterns = patterns('',
    (r'^a/$', ListView.as_view(model=Poll, template_name="a.html")),
    (r'^b/$', ListView.as_view(model=Poll, template_name="b.html")),
)

views.py即使您不需要设置模板。

<强> views.py

class ListView(generic.ListView):
    model = Poll