我在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。我如何解决这个问题?
答案 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