我在使用通用视图的django分页中遇到了一个小问题,将多个模型传递给模板之一,并且需要分页。寻呼机不显示我的模板上的下一页,但只生成一个页面。使用通用视图创建django分页
下面是我的代码:
views.py:
class homeView(generic.ListView):
template_name = 'success/home_page.html'
context_object_name="articles"
paginate_by = 3
def get_queryset(self):
articles =Articles.objects.order_by('article_title')
paginator = Paginator(articles,self.paginate_by)
page = self.request.GET.get('page')
try:
articles = paginator.page(page)
except PageNotAnInteger:
articles = paginator.page(1)
except EmptyPage:
articles = paginator.page(paginator.num_pages)
return articles
def get_context_data(self,**kwargs):
context = super(homeView, self).get_context_data(**kwargs)
context['quote'] = Quotes.objects.order_by('quote')
return context
模板:我的分页页面显示
{% for article in articles %}
{{ article.article_title}}
{{ article.aticle_hit}}
{% endfor % %}
<div class="pagination">
{% if articles.has_previous %}
<a class="navlink" href="?page={{articles.previous_page_number}}">Prev</a>
{% endif %}
Page {{articles.number}} of {{articles.paginator.num_pages}}
{% if articles.has_next %}
<a class="navlink" href="?page={{articles.next_page_number}}">next</a>
{% endif %}
</div>
刚刚页面之一。下一个和上一个根本不起作用。请帮助我更好地使用通用视图进行分页,并将多个模型传递到单个模板。
你为什么要手动做这个?您可以删除整个'get_queryset'方法,只需设置'model = Articles'并保留paginate_by。它会自动工作。 – Melvyn
get_queryset,因为我将两个模型传递给一个模板。我正面临着我的分页问题,不会显示html模板上的下一个和上一个页面 – Scofield
但是,您并未在get_queryset()中创建两个模型。相信我,你不需要get_queryset。删除它,添加模型,保持paginate_by。然后看看它是否仍然无效,导致一切看起来很正常。 – Melvyn