2011-07-30 75 views
2

我嘗試實現分頁到基於類的通用視圖,並以我做到的方式,這是行不通的。如何在基於類的通用視圖中使用分頁?

網址

url(r'^cat/(?P<category>[\w+\s]*)/page(?P<page>[0-9]+)/$', 
    CategorizedPostsView.as_view(), {'paginate_by': 3}), 

視圖

class CategorizedPostsView(ListView): 
    template_name = 'categorizedposts.djhtml' 
    context_object_name = 'post_list' 

    def get_queryset(self): 
     cat = unquote(self.kwargs['category']) 
     category = get_object_or_404(ParentCategory, category=cat) 
     return category.postpages_set.all() 

模板

<div class="pagination"> 
    <span class="step-links"> 
     {% if post_list.has_previous %} 
      <a href="?page={{ post_list.previous_page_number }}">previous</a> 
     {% endif %} 

     <span class="current"> 
      Page {{ post_list.number }} of {{ post_list.paginator.num_pages }}. 
     </span> 

     {% if post_list.has_next %} 
      <a href="?page={{ post_list.next_page_number }}">next</a> 
     {% endif %} 
    </span> 
</div> 

當我試圖讓HTTP:// 127.0.0.1:8000/cat/category_name/?page = 1甚至http:// 127.0.0.1:8000/cat/category_name/我得到了404異常。

如何以正確的方式在基於類的通用視圖中使用分頁? 。

回答

4

哎已經有一個kwarg paginate_byListView所以只是通過它在 嘗試是這樣的:

url(r'^cat/(?P<category>[\w+\s]*)/page(?P<page>[0-9]+)/$', 
    CategorizedPostsView.as_view(paginate_by=3)), 

,併爲您的模板,你可以嘗試像:

{% if is_paginated %} 
    <div class="pagination"> 
     <span class="step-links"> 
      {% if page_obj.has_previous %} 
       <a href="?page={{ page_obj.previous_page_number }}">previous</a> 
      {% endif %} 

      <span class="current"> 
       Page {{ page_obj.number }} of {{ paginator.num_pages }}. 
      </span> 

      {% if page_obj.has_next %} 
       <a href="?page={{ page_obj.next_page_number }}">next</a> 
      {% endif %} 
     </span> 
    </div> 
{% endif %} 
+1

謝謝。和URL會更簡單 - 'url(r'^ cat /(?P [\ w + \ s] *)/ $,CategorizedPostsView.as_view(paginate_by = 3)),' 對於get方法顯式聲明url沒有必要。 – I159

相關問題