Django - 分頁

Django - 分頁

自定義分頁

初版

def publisher_list(request):
    # 從URL中取當前訪問的頁碼數
    try:
        current_page = int(request.GET.get('page'))
    except Exception as e:
        # 取不到或者頁碼數不是數字都默認展現第1頁
        current_page = 1
    # 總數據量
    total_count = models.Publisher.objects.count()
    # 定義每頁顯示多少條數據
    per_page = 10
    # 計算出總頁碼數
    total_page, more = divmod(total_count, per_page)
    if more:
        total_page += 1
    # 定義頁面上最多顯示多少頁碼(爲了左右對稱,通常設爲奇數)
    max_show = 11
    half_show = max_show // 2
    # 計算一下頁面顯示的頁碼範圍
    if total_page <= max_show:  # 總頁碼數小於最大顯示頁碼數
        page_start = 1
        page_end = total_page
    elif current_page + half_show >= total_page:  # 右邊越界
        page_end = total_page
        page_start = total_page - max_show
    elif current_page - half_show <= 1:  # 左邊越界
        page_start = 1
        page_end = max_show
    else:  # 正常頁碼區間
        page_start = current_page - half_show
        page_end = current_page + half_show
    # 數據索引發始位置
    data_start = (current_page-1) * per_page
    data_end = current_page * per_page

    publisher_list = models.Publisher.objects.all()[data_start:data_end]

    # 生成頁面上顯示的頁碼
    page_html_list = []
    page_html_list.append('<nav aria-label="Page navigation"><ul class="pagination">')
    # 加首頁
    first_li = '<li><a href="/publisher_list/?page=1">首頁</a></li>'
    page_html_list.append(first_li)
    # 加上一頁
    if current_page == 1:
        prev_li = '<li><a href="#"><span aria-hidden="true">&laquo;</span></a></li>'
    else:
        prev_li = '<li><a href="/publisher_list/?page={}"><span aria-hidden="true">&laquo;</span></a></li>'.format(current_page - 1)
    page_html_list.append(prev_li)
    for i in range(page_start, page_end + 1):
        if i == current_page:
            li_tag = '<li class="active"><a href="/publisher_list/?page={0}">{0}</a></li>'.format(i)
        else:
            li_tag = '<li><a href="/publisher_list/?page={0}">{0}</a></li>'.format(i)
        page_html_list.append(li_tag)
    # 加下一頁
    if current_page == total_page:
        next_li = '<li><a href="#"><span aria-hidden="true">&raquo;</span></a></li>'
    else:
        next_li = '<li><a href="/publisher_list/?page={}"><span aria-hidden="true">&raquo;</span></a></li>'.format(current_page + 1)
    page_html_list.append(next_li)
    # 加尾頁
    page_end_li = '<li><a href="/publisher_list/?page={}">尾頁</a></li>'.format(total_page)
    page_html_list.append(page_end_li)
    page_html_list.append('</ul></nav>')
    page_html = "".join(page_html_list)
    return render(request, "publisher_list.html", {"publisher_list": publisher_list, "page_html": page_html})

第二版

class Pagination(object):
    """自定義分頁(Bootstrap版)"""
    def __init__(self, current_page, total_count, base_url, per_page=10, max_show=11):
        """
        :param current_page: 當前請求的頁碼
        :param total_count: 總數據量
        :param base_url: 請求的URL
        :param per_page: 每頁顯示的數據量,默認值爲10
        :param max_show: 頁面上最多顯示多少個頁碼,默認值爲11
        """
        try:
            self.current_page = int(current_page)
        except Exception as e:
            # 取不到或者頁碼數不是數字都默認展現第1頁
            self.current_page = 1
        # 定義每頁顯示多少條數據
        self.per_page = per_page
        # 計算出總頁碼數
        total_page, more = divmod(total_count, per_page)
        if more:
            total_page += 1
        self.total_page = total_page
        # 定義頁面上最多顯示多少頁碼(爲了左右對稱,通常設爲奇數)
        self.max_show = max_show
        self.half_show = max_show // 2
        self.base_url = base_url

    @property
    def start(self):
        return (self.current_page-1) * self.per_page

    @property
    def end(self):
        return self.current_page * self.per_page

    def page_html(self):
        # 計算一下頁面顯示的頁碼範圍
        if self.total_page <= self.max_show:  # 總頁碼數小於最大顯示頁碼數
            page_start = 1
            page_end = self.total_page
        elif self.current_page + self.half_show >= self.total_page:  # 右邊越界
            page_end = self.total_page
            page_start = self.total_page - self.max_show
        elif self.current_page - self.half_show <= 1:  # 左邊越界
            page_start = 1
            page_end = self.max_show
        else:  # 正常頁碼區間
            page_start = self.current_page - self.half_show
            page_end = self.current_page + self.half_show
        # 生成頁面上顯示的頁碼
        page_html_list = []
        page_html_list.append('<nav aria-label="Page navigation"><ul class="pagination">')
        # 加首頁
        first_li = '<li><a href="{}?page=1">首頁</a></li>'.format(self.base_url)
        page_html_list.append(first_li)
        # 加上一頁
        if self.current_page == 1:
            prev_li = '<li><a href="#"><span aria-hidden="true">&laquo;</span></a></li>'
        else:
            prev_li = '<li><a href="{}?page={}"><span aria-hidden="true">&laquo;</span></a></li>'.format(
                self.base_url, self.current_page - 1)
        page_html_list.append(prev_li)
        for i in range(page_start, page_end + 1):
            if i == self.current_page:
                li_tag = '<li class="active"><a href="{0}?page={1}">{1}</a></li>'.format(self.base_url, i)
            else:
                li_tag = '<li><a href="{0}?page={1}">{1}</a></li>'.format(self.base_url, i)
            page_html_list.append(li_tag)
        # 加下一頁
        if self.current_page == self.total_page:
            next_li = '<li><a href="#"><span aria-hidden="true">&raquo;</span></a></li>'
        else:
            next_li = '<li><a href="{}?page={}"><span aria-hidden="true">&raquo;</span></a></li>'.format(
                self.base_url, self.current_page + 1)
        page_html_list.append(next_li)
        # 加尾頁
        page_end_li = '<li><a href="{}?page={}">尾頁</a></li>'.format(self.base_url, self.total_page)
        page_html_list.append(page_end_li)
        page_html_list.append('</ul></nav>')
        return "".join(page_html_list)

第三版

def publisher_list(request):
    # 從URL中取當前訪問的頁碼數
    current_page = int(request.GET.get('page'))
    # 比len(models.Publisher.objects.all())更高效
    total_count = models.Publisher.objects.count()
    page_obj = Pagination(current_page, total_count, request.path_info)
    data = models.Publisher.objects.all()[page_obj.start:page_obj.end]
    page_html = page_obj.page_html()
    return render(request, "publisher_list.html", {"publisher_list": data, "page_html": page_html})

Django內置分頁

view.pydjango

from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

L = []
for i in range(999):
    L.append(i)

def index(request):
    current_page = request.GET.get('p')

    paginator = Paginator(L, 10)
    # per_page: 每頁顯示條目數量
    # count:    數據總個數
    # num_pages:總頁數
    # page_range:總頁數的索引範圍,如: (1,10),(1,200)
    # page:     page對象
    try:
        posts = paginator.page(current_page)
        # has_next              是否有下一頁
        # next_page_number      下一頁頁碼
        # has_previous          是否有上一頁
        # previous_page_number  上一頁頁碼
        # object_list           分頁以後的數據列表
        # number                當前頁
        # paginator             paginator對象
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)
    return render(request, 'index.html', {'posts': posts})

HTMLapp

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<ul>
    {% for item in posts %}
        <li>{{ item }}</li>
    {% endfor %}
</ul>

<div class="pagination">
      <span class="step-links">
        {% if posts.has_previous %}
            <a href="?p={{ posts.previous_page_number }}">Previous</a>
        {% endif %}
          <span class="current">
            Page {{ posts.number }} of {{ posts.paginator.num_pages }}.
          </span>
          {% if posts.has_next %}
              <a href="?p={{ posts.next_page_number }}">Next</a>
          {% endif %}
      </span>

</div>
</body>
</html>
相關文章
相關標籤/搜索