温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在Python中使用Django实现简单分页

发布时间:2021-06-03 17:03:16 来源:亿速云 阅读:150 作者:Leah 栏目:开发技术

本篇文章给大家分享的是有关怎么在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实现简单分页,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI