使用通用视图创建django分页

时间:2017-06-21 23:04:48

标签: django html5

我在使用通用视图的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>

只是我的分页页面显示的第一页。下一个和上一个根本不起作用。请帮助我更好地使用通用视图进行分页并将多个模型传递到单个模板中。

1 个答案:

答案 0 :(得分:0)

如上所述,减少。如果您收到错误,请发布,这将有所帮助。

class homeView(generic.ListView):
    template_name = 'success/home_page.html'
    context_object_name = "articles"
    paginate_by = 3
    model = Articles

    def get_context_data(self, **kwargs):
        context = super(homeView, self).get_context_data(**kwargs)
        context['quote'] = Quotes.objects.order_by('quote')
        return context