首頁 > Python教程 > Python應用 > Django框架教程:Pagination分頁實現代碼實例

Django框架教程:Pagination分頁實現代碼實例

時間:2019-09-15    作者:高~雅   來源:互聯網

一、自定義分頁

1、基礎版自定義分頁

data = []
 
for i in range(1, 302):
  tmp = {"id": i, "name": "alex-{}".format(i)}
  data.append(tmp)
 
print(data)
def user_list(request):
 
  # user_list = data[0:10]
  # user_list = data[10:20]
  try:
    current_page = int(request.GET.get("page"))
  except Exception as e:
    current_page = 1
 
  per_page = 10
 
  # 數據總條數
  total_count = len(data)
  # 總頁碼
  total_page, more = divmod(total_count, per_page)
  if more:
    total_page += 1
 
  # 頁面最多顯示多少個頁碼
  max_show = 11
  half_show = int((max_show-1)/2)
 
  if current_page <= half_show:
    show_start = 1
    show_end = max_show
  else:
    if current_page + half_show >= total_page:
      show_start = total_page - max_show
      show_end = total_page
    else:
      show_start = current_page - half_show
      show_end = current_page + half_show
 
  # 數據庫中獲取數據
  data_start = (current_page - 1) * per_page
  data_end = current_page * per_page
 
  user_list = data[data_start:data_end]
 
  # 生成頁面上顯示的頁碼
  page_html_list = []
  # 加首頁
  first_li = '<li><a href="/user_list/?page=1" rel="external nofollow" >首頁</a></li>'
  page_html_list.append(first_li)
  # 加上一頁
  if current_page == 1:
    prev_li = '<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >上一頁</a></li>'
  else:
    prev_li = '<li><a href="/user_list/?page={}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >上一頁</a></li>'.format(current_page - 1)
  page_html_list.append(prev_li)
  for i in range(show_start, show_end+1):
    if i == current_page:
      li_tag = '<li class="active"><a href="/user_list/?page={0}" rel="external nofollow" rel="external nofollow" >{0}</a></li>'.format(i)
    else:
      li_tag = '<li><a href="/user_list/?page={0}" rel="external nofollow" rel="external nofollow" >{0}</a></li>'.format(i)
    page_html_list.append(li_tag)
 
  # 加下一頁
  if current_page == total_page:
    next_li = '<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >下一頁</a></li>'
  else:
    next_li = '<li><a href="/user_list/?page={}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >下一頁</a></li>'.format(current_page+1)
  page_html_list.append(next_li)
 
  # 加尾頁
  page_end_li = '<li><a href="/user_list/?page={}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >尾頁</a></li>'.format(total_page)
  page_html_list.append(page_end_li)
 
  page_html = "".join(page_html_list)
 
  return render(request, "user_list.html", {"user_list": user_list, "page_html": page_html})

2、封裝保存版

class Pagination(object):
  def __init__(self, current_page, total_count, base_url, per_page=10, max_show=11):
    """
    :param current_page: 當前頁
    :param total_count: 數據庫中數據總數
    :param per_page: 每頁顯示多少條數據
    :param max_show: 最多顯示多少頁
    """
    try:
      current_page = int(current_page)
    except Exception as e:
      current_page = 1
 
    self.current_page = current_page
    self.total_count = total_count
    self.base_url = base_url
    self.per_page = per_page
    self.max_show = max_show
 
    # 總頁碼
    total_page, more = divmod(total_count, per_page)
    if more:
      total_page += 1
     
    half_show = int((max_show - 1) / 2)
    self.half_show = half_show
    self.total_page = total_page
 
  @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.current_page <= self.half_show:
      show_start = 1
      show_end = self.max_show
    else:
      if self.current_page + self.half_show >= self.total_page:
        show_start = self.total_page - self.max_show
        show_end = self.total_page
      else:
        show_start = self.current_page - self.half_show
        show_end = self.current_page + self.half_show
 
        # 生成頁面上顯示的頁碼
    page_html_list = []
    # 加首頁
    first_li = '<li><a href="{}?page=1" rel="external nofollow" >首頁</a></li>'.format(self.base_url)
    page_html_list.append(first_li)
    # 加上一頁
    if self.current_page == 1:
      prev_li = '<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >上一頁</a></li>'
    else:
      prev_li = '<li><a href="{0}?page={1}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >上一頁</a></li>'.format(self.base_url, self.current_page - 1)
    page_html_list.append(prev_li)
    for i in range(show_start, show_end + 1):
      if i == self.current_page:
        li_tag = '<li class="active"><a href="{0}?page={1}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{1}</a></li>'.format(self.base_url, i)
      else:
        li_tag = '<li><a href="{0}?page={1}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{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="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >下一頁</a></li>'
    else:
      next_li = '<li><a href="{0}?page={1}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >下一頁</a></li>'.format(self.base_url, self.current_page + 1)
    page_html_list.append(next_li)
 
    # 加尾頁
    page_end_li = '<li><a href="{0}?page={1}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >尾頁</a></li>'.format(self.base_url, self.total_page)
    page_html_list.append(page_end_li)
     return "".join(page_html_list)

3、封裝保存版使用指南

def user_list(request):
  pager = Pagination(request.GET.get("page"), len(data), request.path_info)
  user_list = data[pager.start:pager.end]
  page_html = pager.page_html()
  return render(request, "user_list.html", {"user_list": user_list, "page_html": page_html})

二、Django內置分頁

1、內置分頁view部分

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}) 

2、內置分頁HTML部分

<!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 }}" rel="external nofollow" >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 }}" rel="external nofollow" >Next</a>
     {% endif %}
   </span>
</div>
</body>
</html>

以上就是本文的全部內容,希望對大家的學習有所幫助

相關推薦
用Python爬取B站5000 條視頻,揭秘為何千萬人為它流淚!
Python教程:如何用xlrd和xlwt庫讀和寫Excel表格?
Python安裝MySQL-python:EnvironmentError的解決辦法
分享:Python2和Python3有那些差異?
Python 的內置對象都藏了哪些小秘密?
實戰干貨!用案例讓你一文搞懂python網絡爬蟲
Python教程:圖像處理模塊ndimage用法實例分析
Python教程:代理IP爬蟲的使用方法
Python教程:如何使用scipy模塊實現一維卷積運算示例?
Python:關于內存分配時的那些小秘密分享
python技巧:global關鍵字的用法詳解
Python教程:深入了解python在HDA中的應用
python技巧:SSLerror的requests證書問題解決方法
PyCharm教程:搭建Spark開發環境的幾個步驟
Python開發技巧:openpyxl讀取單元格字體顏色過程解析
Python教程:面向對象之Web靜態服務器
Python教程:如何為終端提供持久性歷史記錄
Python技巧分享:自動登錄淘寶并保存登錄信息的方法
Python數據分析:利用Flask動態展示 Pyecharts 圖表數據方法
python3教程:如何搭建微型的web服務器?
python技巧:xlwt如何設置單元格的自定義背景顏色
如何解決Python字符串和正則表達式中的反斜杠('\')問題?
Python開發技巧:編寫一個簡單登錄功能過程解析
Python編程:postman傳遞當前時間戳實例詳解
Python爬蟲教程:使用beautifulSoup4爬取名言網案例代碼分享
python開發:動態遷移solr數據過程分享
python數據分析:用線性回歸預測股票價格的代碼分析
Python教程:數據分析模塊pandas用法詳解
Python3教程:pandas.merge用法詳解
Python爬蟲案例:如何爬取豆瓣電影信息?附代碼實例
python開發:如何編寫簡單端口掃描器?

精彩推薦

熱門教程

北京pk10走势图下载 福彩3d和值走势图双彩网 亲朋棋牌游戏大厅下载 怎样可以手机上赚钱 浙江舟山飞鱼开奖结果 博远棋牌注册 海南环岛赛开奖查询 pk10九码都有什么玩法 阿里巴巴股票分析图 北京快乐8死人 中国股票指数有哪些 青海十一选五玩法 游戏场景设计赚钱吗