1. 程式人生 > 實用技巧 >Django基礎06篇 分頁

Django基礎06篇 分頁

1.匯入Django自帶的分頁類

from django.core.paginator import Paginator

2.分頁類的使用

def index(request):
    # return HttpResponse('hello django!')
    limit = request.GET.get('limit',5)
    page_number = request.GET.get('page',1)
    articles = models.Article.objects.all()
    page = Paginator(articles,limit)  #
分頁後的物件 articles = page.page(page_number) # 當前頁的資料 print(articles.has_next()) # 有沒有下一頁 # print(articles.next_page_number())#下一頁的頁碼,有下一頁的話才有 print(articles.has_other_pages()) # 有沒有其他頁 print(articles.has_previous()) # 有沒有上一頁 # print(articles.previous_page_number())#上一頁的頁碼 print
(articles.number) # 當前頁的頁碼 print(articles.start_index()) # 當前這一頁的第一條資料的下標 print(articles.end_index()) # 當前這一頁的最後一條資料的下標 # articles.paginator #就是上面分頁完之後的物件 print(page.num_pages) # 總共多少頁 print(page.page_range) # 分頁的範圍 1 2 3 4 # articles.paginator.num_pages # title = 'my blog'
return render(request, 'index.html', {'articles': articles})

3.前端程式碼中使用

<div class="text-center mt-2 mt-sm-1 mt-md-0 mb-3 f-16">
                    {% if articles.has_previous %}
                        <a class="text-success" href="?page={{ articles.previous_page_number }}">上一頁</a>
                    {% else %}
                        <span class="text-secondary" title="當前頁已經是首頁">上一頁</span>
                    {% endif %}
                    <span class="mx-2">&nbsp;{{ articles.number }}&nbsp;/&nbsp;{{ articles.paginator.num_pages }}&nbsp;</span>
                    {% if articles.has_next %}
                        <a class="text-success" href="?page={{ articles.next_page_number }}">下一頁</a>
                    {% else %}
                        <span class="text-secondary" title="當前頁已經是尾頁">下一頁</span>
                    {% endif %}


                </div>
index.html