Python Django 添加首页尾页上一页下一页代码实例

添加首页和尾页:

views.py:

from django.shortcuts import render
from app01 import models
def book_list(request):
  # 从 URL 中取参数
  page_num = request.GET.get("page")
  print(page_num, type(page_num))
  page_num = int(page_num)
  # 定义两个变量保存数据从哪儿取到哪儿
  data_start = (page_num - 1) * 10
  data_end = page_num * 10
  # 书籍总数
  total_count = models.Book.objects.all().count()
  # 每一页显示多少条数据
  per_page = 10
  # 总共需要多少页码来显示
  total_page, m = divmod(total_count, per_page)
  # 页面上最多展示的页码
  max_page = 11
  half_max_page = max_page // 2

  # 页面上展示的页码的开始页
  page_start = page_num - half_max_page
  # 页面上展示的页码的结束页
  page_end = page_num + half_max_page
  # 如果当前页减一半比 1 小
  if page_start <= 1:
    page_start = 1
    page_end = max_page
  # 如果当前页加一半比总页码还大
  if page_end > total_page:
    page_end = total_page
    page_start = total_page - max_page + 1
  # 如果还有数据
  if m:
    total_page += 1
  all_book = models.Book.objects.all()[data_start:data_end]
  # 拼接 html 的分页代码
  html_list = []
  # 添加首页按钮
  html_list.append('<li><a href="/books/?page=1" rel="external nofollow" >首页</a></li>')
  # 展示的页码
  for i in range(page_start, page_end + 1):
    tmp = '<li><a href="/book_list/?page={0}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{0}</a></li>'.format(i)
    html_list.append(tmp)
  # 添加尾页按钮
  html_list.append('<li><a href="/books/?page={}" rel="external nofollow" >尾页</a></li>'.format(total_page))
  page_html = "".join(html_list) # 拼接 html 的分页代码
  return render(request, "book_list.html", {"books": all_book, "page_html": page_html})

book_list.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>书籍列表</title>
  <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" >
</head>
<body>
<div class="container">
  <table class="table table-bordered">
    <thead>
    <tr>
      <th>序号</th>
      <th>id</th>
      <th>书名</th>
    </tr>
    </thead>
    <tbody>
    {% for book in books %}
      <tr>
        <td>{{ forloop.counter }}</td>
        <td>{{ book.id }}</td>
        <td>{{ book.title }}</td>
      </tr>
    {% endfor %}
    </tbody>
  </table>
  <nav aria-label="Page navigation">
    <ul class="pagination">
      <li>
        {{ page_html|safe }}
      </li>
    </ul>
  </nav>
</div>
</body>
</html>

运行结果:

添加上一页、下一页:

views.py:

from django.shortcuts import render
from app01 import models
def book_list(request):
  # 从 URL 中取参数
  page_num = request.GET.get("page")
  print(page_num, type(page_num))
  page_num = int(page_num)
  # 定义两个变量保存数据从哪儿取到哪儿
  data_start = (page_num - 1) * 10
  data_end = page_num * 10
  # 书籍总数
  total_count = models.Book.objects.all().count()
  # 每一页显示多少条数据
  per_page = 10
  # 总共需要多少页码来显示
  total_page, m = divmod(total_count, per_page)
  # 页面上最多展示的页码
  max_page = 11
  half_max_page = max_page // 2
  # 页面上展示的页码的开始页
  page_start = page_num - half_max_page
  # 页面上展示的页码的结束页
  page_end = page_num + half_max_page
  # 如果当前页减一半比 1 小
  if page_start <= 1:
    page_start = 1
    page_end = max_page
  # 如果当前页加一半比总页码还大
  if page_end > total_page:
    page_end = total_page
    page_start = total_page - max_page + 1
  # 如果还有数据
  if m:
    total_page += 1
  all_book = models.Book.objects.all()[data_start:data_end]
  # 拼接 html 的分页代码
  html_list = []
  # 添加首页按钮
  html_list.append('<li><a href="/book_list/?page=1" rel="external nofollow" rel="external nofollow" rel="external nofollow" >首页</a></li>')
  # 如果是第一页,就没有上一页
  if page_num <= 1:
    html_list.append('<li class="disabled"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span aria-hidden="true">«</span></a></li>'.format(page_num-1))
  else:
    # 加一个上一页的标签
    html_list.append('<li><a href="/book_list/?page={}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span aria-hidden="true">«</span></a></li>'.format(page_num-1))
  # 展示的页码
  for i in range(page_start, page_end + 1):
    # 给当前页添加 active
    if i == page_num:
      tmp = '<li class="active"><a href="/book_list/?page={0}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{0}</a></li>'.format(i)
    else:
      tmp = '<li><a href="/book_list/?page={0}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{0}</a></li>'.format(i)
    html_list.append(tmp)
  # 如果是最后一页,就没有下一页
  if page_num >= total_page:
    html_list.append('<li class="disabled"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span aria-hidden="true">»</span></a></li>')
  else:
    html_list.append('<li><a href="/book_list/?page={}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span aria-hidden="true">»</span></a></li>'.format(page_num+1))
  # 添加尾页按钮
  html_list.append('<li><a href="/book_list/?page={}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >尾页</a></li>'.format(total_page))

  page_html = "".join(html_list) # 拼接 html 的分页代码
  return render(request, "book_list.html", {"books": all_book, "page_html": page_html})

book_list.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>书籍列表</title>
  <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" >
</head>
<body>
<div class="container">
  <table class="table table-bordered">
    <thead>
    <tr>
      <th>序号</th>
      <th>id</th>
      <th>书名</th>
    </tr>
    </thead>
    <tbody>
    {% for book in books %}
      <tr>
        <td>{{ forloop.counter }}</td>
        <td>{{ book.id }}</td>
        <td>{{ book.title }}</td>
      </tr>
    {% endfor %}
    </tbody>
  </table>
  <nav aria-label="Page navigation">
    <ul class="pagination">
      <li>
        {{ page_html|safe }}
      </li>
    </ul>
  </nav>
</div>
</body>
</html>

运行结果:

后续改进:

处理用户传给 url 的 page 参数异常的值的情况

例如:

访问,http://127.0.0.1:8888/book_list/?page=a

访问,http://127.0.0.1:8888/book_list/?page=-1

都会出错

改进:

from django.shortcuts import render
from app01 import models
def book_list(request):
  # 从 URL 中取参数
  page_num = request.GET.get("page")
  print(page_num, type(page_num)) # page_num 为 str 类型
  # 书籍总数
  total_count = models.Book.objects.all().count()
  # 每一页显示多少条数据
  per_page = 10
  # 总共需要多少页码来显示
  total_page, m = divmod(total_count, per_page)
  # 如果还有数据
  if m:
    total_page += 1
  try:
    page_num = int(page_num)
    # 如果输入的页码数超过了最大的页码数,默认返回最后一页
    if page_num > total_page:
      page_num = total_page
    # 如果输入的页码数小于 1,则返回第一页
    if page_num < 1:
      page_num = 1
  except Exception as e:
    # 当输入的页码不是正经数字的时候 默认返回第一页的数据
    page_num = 1
  # 定义两个变量保存数据从哪儿取到哪儿
  data_start = (page_num - 1) * 10
  data_end = page_num * 10
  # 页面上最多展示的页码
  max_page = 11
  half_max_page = max_page // 2
  # 页面上展示的页码的开始页
  page_start = page_num - half_max_page
  # 页面上展示的页码的结束页
  page_end = page_num + half_max_page
  # 如果当前页减一半比 1 小
  if page_start <= 1:
    page_start = 1
    page_end = max_page
  # 如果当前页加一半比总页码还大
  if page_end > total_page:
    page_end = total_page
    page_start = total_page - max_page + 1
  all_book = models.Book.objects.all()[data_start:data_end]
  # 拼接 html 的分页代码
  html_list = []
  # 添加首页按钮
  html_list.append('<li><a href="/book_list/?page=1" rel="external nofollow" rel="external nofollow" rel="external nofollow" >首页</a></li>')
  # 如果是第一页,就没有上一页
  if page_num <= 1:
    html_list.append('<li class="disabled"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span aria-hidden="true">«</span></a></li>'.format(page_num-1))
  else:
    # 加一个上一页的标签
    html_list.append('<li><a href="/book_list/?page={}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span aria-hidden="true">«</span></a></li>'.format(page_num-1))
   # 展示的页码
  for i in range(page_start, page_end + 1):
    # 给当前页添加 active
    if i == page_num:
      tmp = '<li class="active"><a href="/book_list/?page={0}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{0}</a></li>'.format(i)
    else:
      tmp = '<li><a href="/book_list/?page={0}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{0}</a></li>'.format(i)
    html_list.append(tmp)
  # 如果是最后一页,就没有下一页
  if page_num >= total_page:
    html_list.append('<li class="disabled"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span aria-hidden="true">»</span></a></li>')
  else:
    html_list.append('<li><a href="/book_list/?page={}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span aria-hidden="true">»</span></a></li>'.format(page_num+1))
  # 添加尾页按钮
  html_list.append('<li><a href="/book_list/?page={}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >尾页</a></li>'.format(total_page))

  page_html = "".join(html_list) # 拼接 html 的分页代码
  return render(request, "book_list.html", {"books": all_book, "page_html": page_html})

如果数据库中的数据数少于 max_page,则会显示负数的页数

例如数据库中只有 21 条数据:

改进:

from django.shortcuts import render
from app01 import models
def book_list(request):
  # 从 URL 中取参数
  page_num = request.GET.get("page")
  print(page_num, type(page_num)) # page_num 为 str 类型
  # 书籍总数
  total_count = models.Book.objects.all().count()
  # 每一页显示多少条数据
  per_page = 10
  # 总共需要多少页码来显示
  total_page, m = divmod(total_count, per_page)
  # 如果还有数据
  if m:
    total_page += 1
  try:
    page_num = int(page_num)
    # 如果输入的页码数超过了最大的页码数,默认返回最后一页
    if page_num > total_page:
      page_num = total_page
    # 如果输入的页码数小于 1,则返回第一页
    if page_num < 1:
      page_num = 1
  except Exception as e:
    # 当输入的页码不是正经数字的时候 默认返回第一页的数据
    page_num = 1
  # 定义两个变量保存数据从哪儿取到哪儿
  data_start = (page_num - 1) * 10
  data_end = page_num * 10
  # 页面上最多展示的页码
  max_page = 11
  # 如果总页码数小于页面上最多展示的页码
  if total_page < max_page:
    max_page = total_page
  half_max_page = max_page // 2
  # 页面上展示的页码的开始页
  page_start = page_num - half_max_page
  # 页面上展示的页码的结束页
  page_end = page_num + half_max_page
  # 如果当前页减一半比 1 小
  if page_start <= 1:
    page_start = 1
    page_end = max_page
  # 如果当前页加一半比总页码还大
  if page_end > total_page:
    page_end = total_page
    page_start = total_page - max_page + 1
  all_book = models.Book.objects.all()[data_start:data_end]
  # 拼接 html 的分页代码
  html_list = []
  # 添加首页按钮
  html_list.append('<li><a href="/book_list/?page=1" rel="external nofollow" rel="external nofollow" rel="external nofollow" >首页</a></li>')
  # 如果是第一页,就没有上一页
  if page_num <= 1:
    html_list.append('<li class="disabled"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span aria-hidden="true">«</span></a></li>'.format(page_num-1))
  else:
    # 加一个上一页的标签
    html_list.append('<li><a href="/book_list/?page={}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span aria-hidden="true">«</span></a></li>'.format(page_num-1))
  # 展示的页码
  for i in range(page_start, page_end + 1):
    # 给当前页添加 active
    if i == page_num:
      tmp = '<li class="active"><a href="/book_list/?page={0}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{0}</a></li>'.format(i)
    else:
      tmp = '<li><a href="/book_list/?page={0}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{0}</a></li>'.format(i)
    html_list.append(tmp)
  # 如果是最后一页,就没有下一页
  if page_num >= total_page:
    html_list.append('<li class="disabled"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span aria-hidden="true">»</span></a></li>')
  else:
    html_list.append('<li><a href="/book_list/?page={}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span aria-hidden="true">»</span></a></li>'.format(page_num+1))
  # 添加尾页按钮
  html_list.append('<li><a href="/book_list/?page={}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >尾页</a></li>'.format(total_page))
  page_html = "".join(html_list) # 拼接 html 的分页代码
  return render(request, "book_list.html", {"books": all_book, "page_html": page_html})

运行结果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • python+django加载静态网页模板解析

    接着前面Django入门使用示例 今天我们来看看Django是如何加载静态html的? 我们首先来看一看什么是静态HTML,什么是动态的HTML?二者有什么区别? 静态HTML指的是使用单纯的HTML或者结合CSS制作的包括图片.文字等的只供用户浏览但不包含任何脚本.不含有任何交互功能的网页! 动态的HTML指的是网页不仅提供给用户浏览,网页本身还有交互功能,存在着在脚本如JAVASCRIPT,并利用某种服务器端语言如PHP等实现如用户注册,用户登录,上传文件,下载文件等功能 接下来,了解下加载

  • 在Python的Django框架中编写错误提示页面

    你应该在生产环境中把TEMPLATE_DEBUGFalse 如果这个设为`` True`` ,为了在那个好看的错误页面上显示足够的东西,Django的模版系统就会为每一个模版保存一些额外的信息. 实现一个404模板 如果`` DEBUG`` 设置为`` True`` ,Django会显示那个自带的404错误页面. 但如果`` DEBUG`` 被设置成`` False`` ,那它的行为就不一样了: 他会显示一个在你的模版根目录中名字叫`` 404.html`` 的模版 所以,当你准备部署你的应用时

  • 使用Python的Django框架结合jQuery实现AJAX购物车页面

    Django中集成jquery 首先,静态的资源通常放入static文件夹中: static/ css/ djquery.css samples/ hello.css js/ jquery-1.7.1.min.js samples/ hello.js 其中css和js都按照应用名称(这里是samples)划分文件夹,如果文件较多,还可以再划分子文件夹. Django通常使用模板来展现html,而且我们通常使用继承的模板,所以需要将共用的元素,比如全局的css,对jquery.js的引入等,写到b

  • 使用python Django做网页

    1 .创建一个django项目使用django-admin.py startproject MyDjangoSite 参考这里 2.建立视图from django.http import HttpResponsedef hello(request):    return HttpResponse("我的第一个简单的python django项目.")3.修改urls.py 我们为urlpatterns加上一行: (r'^hello/$', hello), 这行被称作URLpattern

  • python之django母板页面的使用

    其实就是利用{% block xxx %}   {% endblock %}的方式定义一个块,相当于占位.存放在某个html中,比如base.html 然后在需要实现这些块的文件中,使用继承{% extends "base.html" %}的方式引入母板文件,然后在{% block xxx %}......{% endblock %}块定义中实现具体的内容. base.html示例:注意块的定义. <!DOCTYPE html> <html lang="zh

  • Using Django with GAE Python 后台抓取多个网站的页面全文

    一直想做个能帮我过滤出优质文章和博客的平台 给它取了个名 叫Moven.. 把实现它的过程分成了三个阶段: 1. Downloader: 对于指定的url的下载 并把获得的内容传递给Analyser--这是最简单的开始 2. Analyser: 对于接受到的内容,用Regular Expression 或是 XPath 或是 BeautifulSoup/lxml 进行过滤和简化--这部分也不是太难 3. Smart Crawler: 去抓取优质文章的链接--这部分是最难的: Crawler的话可

  • python中django框架通过正则搜索页面上email地址的方法

    本文实例讲述了python中django框架通过正则搜索页面上email地址的方法.分享给大家供大家参考.具体实现方法如下: import re from django.shortcuts import render from pattern.web import URL, DOM, abs, find_urls def index(request): """ find email addresses in requested url or contact page &quo

  • Python Django 添加首页尾页上一页下一页代码实例

    添加首页和尾页: views.py: from django.shortcuts import render from app01 import models def book_list(request): # 从 URL 中取参数 page_num = request.GET.get("page") print(page_num, type(page_num)) page_num = int(page_num) # 定义两个变量保存数据从哪儿取到哪儿 data_start = (pa

  • Python Django框架单元测试之文件上传测试示例

    本文实例讲述了Python Django框架单元测试之文件上传测试.分享给大家供大家参考,具体如下: Submitting files is a special case. To POST a file, you need only provide the file field name as a key, and a file handle to the file you wish to upload as a value. For example: >>> c = Client()

  • Python爬取当当、京东、亚马逊图书信息代码实例

    注:1.本程序采用MSSQLserver数据库存储,请运行程序前手动修改程序开头处的数据库链接信息 2.需要bs4.requests.pymssql库支持 3.支持多线程 from bs4 import BeautifulSoup import re,requests,pymysql,threading,os,traceback try: conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root',

  • python操作openpyxl导出Excel 设置单元格格式及合并处理代码实例

    这篇文章主要介绍了python操作openpyxl导出Excel 设置单元格格式及合并处理代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 贴上一个例子,里面设计很多用法,根据将相同日期的某些行合并处理. from openpyxl import Workbook from openpyxl.styles import Font, Fill, Alignment, Border, Side, PatternFill from handle

  • python各层级目录下import方法代码实例

    这篇文章主要介绍了python各层级目录下import方法代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 以前经常使用python2.现在很多东西都切换到了python3,发现很多东西还是存在一些差异化的.跨目录import是常用的一种方法,并且有不同的表现形式,新手很容易搞混.有必要这里做个总结,给大家科普一下: 1 同级目录下的调用: 同级目录下的调用比较简单,一般使用场景是不同类的相互调用.不用考虑路径问题,常用的格式是:from

  • html5以及jQuery实现本地图片上传前的预览代码实例讲解

    html5以及jQuery实现本地图片上传前的预览,效果类似如下: 选择图片前的页面: 选择图片之后的预览效果: 下面直接上代码(只是最简单的实现代码,css样式没有复制,自己随意发挥) <!DOCTYPE html> <html> <head> <title>HTML5上传图片预览</title> <meta http-equiv="Content-Type" content="text/html; char

  • Python通过递归获取目录下指定文件代码实例

    这篇文章主要介绍了python通过递归获取目录下指定文件代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 获取一个目录下所有指定格式的文件是实际生产中常见需求. import os #递归获取一个目录下所有的指定格式的文件 def get_jsonfile(path,file_list): dir_list=os.listdir(path) for x in dir_list: new_x=os.path.join(path,x) if

  • Python模拟登陆淘宝并统计淘宝消费情况的代码实例分享

    支付宝十年账单上的数字有点吓人,但它统计的项目太多,只是想看看到底单纯在淘宝上支出了多少,于是写了段脚本,统计任意时间段淘宝订单的消费情况,看那结果其实在淘宝上我还是相当节约的说. 脚本的主要工作是模拟了浏览器登录,解析"已买到的宝贝"页面以获得指定的订单及宝贝信息. 使用方法见代码或执行命令加参数-h,另外需要BeautifulSoup4支持,BeautifulSoup的官方项目列表页:https://www.crummy.com/software/BeautifulSoup/bs4

  • Python+django实现简单的文件上传

    今天分享一下Django实现的简单的文件上传的小例子. 步骤  •创建Django项目,创建Django应用  •设计模型  •处理urls.py 以及views.py  •设计模板,设计表单  •运行项目,查看数据库 下面我们就一起来分别完成每一个小部分吧. 创建项目和应用 django-admin startproject Django_upload django-admin startapp app 添加一个名为upload的目录,待会要用哦. 然后记得在settings.py 中的INS

  • 基于SpringBoot实现上传2种方法工程代码实例

    创建SpringBoot工程: 再导入所需要的依赖: <dependency> <groupId>net.oschina.zcx7878</groupId> <artifactId>fastdfs-client-java</artifactId> <version>1.27.0.0</version> </dependency> <dependency> <groupId>org.apa

随机推荐