如何对两个不同的模板使用ListView类

2024-10-02 12:36:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我在view.py中有一个ListView

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.How方法我能解决这个问题吗?你知道吗


Tags: djangonamefromimportgetindexobjecthtml
2条回答

urls.py中,可以将template_name设置为ListViewurl entry router的属性。你知道吗

网址.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中,即使您不需要设置模板。你知道吗

视图.py

class ListView(generic.ListView):
    model = Poll

使用混合液:

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 %}

相关问题 更多 >

    热门问题