Python Django 简单分页的实现代码解析

yipeiwu_com5年前Python基础

这篇文章主要介绍了Python Django 简单分页的实现代码解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

models.py:

from django.db import models
class Book(models.Model):
  title = models.CharField(max_length=32)
  def __str__(self):
    return self.title
  class Meta:
    db_table = "books"

批量创建 106 条数据

import os
if __name__ == '__main__':
  os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite3.settings")
  import django
  django.setup()
  from app01 import models
  # 106 个书籍对象
  objs = [models.Book(title="《Python 的故事第{}版》".format(i)) for i in range(116)]
  # 在数据库中批量创建, 10 次一提交
  models.Book.objects.bulk_create(objs, 10)

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)
  if m:
    total_page += 1 
  all_book = models.Book.objects.all()[data_start:data_end]
 
  # 拼接 html 的分页代码
  html_list = []
  for i in range(1, total_page+1):
    tmp = '<li><a href="/book_list/?page={0}" rel="external nofollow" >{0}</a></li>'.format(i)
    html_list.append(tmp) 
  page_html = "".join(html_list) 
  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" >
</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">
      {{ page_html|safe }}
    </ul>
  </nav> 
</div>
</body>
</html>

运行结果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

如何通过Django使用本地css/js文件

这篇文章主要介绍了如何通过Django使用本地css/js文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在网上看了很多说Djan...

python实现文件的分割与合并

使用Python来进行文件的分割与合并是非常简单的。 python代码如下: splitFile--将文件分割成大小为chunksize的块; mergeFile--将众多文件块合并成原...

Python原始字符串与Unicode字符串操作符用法实例分析

Python原始字符串与Unicode字符串操作符用法实例分析

本文实例讲述了Python原始字符串与Unicode字符串操作符用法。分享给大家供大家参考,具体如下: #coding=utf8 ''''' 在原始字符串里,所有的字符串都是直接按照...

Python 实现将数组/矩阵转换成Image类

Python 实现将数组/矩阵转换成Image类

先说明一下为什么要将数组转换成Image类。我处理的图像是FITS (Flexible Image Transport System)文件,是一种灰度图像文件,也就是单通道图像。 FIT...

Windows上使用Python增加或删除权限的方法

在使用Python在 Windows 平台上开发的时候, 有时候我们需要动态增加或删除用户的某些权限, 此时我们可以通过 AdjustTokenPrivileges API 来实现。 比...