search
HomeBackend DevelopmentPython TutorialImplementation code of Django custom paging in python

The content of this article is about the implementation code of Django custom paging in python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Custom paging

Steady and steady version

def book(request):
    # 从URL取参数(访问的页码)
    page_num = request.GET.get("page")
    try:
        # 将取出的page转换为int类型
        page_num = int(page_num)
    except Exception as e:
        # 当输入的页码不是正经数字的时候 默认返回第一页的数据
        page_num = 1

    # 数据库总数据是多少条
    total_count = models.Book.objects.all().count()

    # 每一页显示多少条数据
    per_page = 10

    # 总共需要多少页码来展示
    total_page, m = divmod(total_count, per_page)
    if m:
        total_page += 1

    # 如果输入的页码数超过了最大的页码数,默认返回最后一页
    if page_num > total_page:
        page_num = total_page

    # 定义两个变量从哪里开始到哪里结束
    data_start = (page_num - 1) * 10
    data_end = page_num * 10

    # 页面上总共展示多少页码
    max_page = 11
    if total_page < max_page:
        max_page = total_page

    # 把从URL中获取的page_num 当做是显示页面的中间值, 那么展示的便是当前page_num 的前五页和后后五页
    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_str_list = []

    # # 加上首页
    html_str_list.append(&#39;<li><a href="/book/?page=1">首页</a></li>&#39;)

    # 断一下 如果是第一页,就没有上一页
    if page_num <= 1:
        html_str_list.append(&#39;<li class="disabled"><a href="#"><span aria-hidden="true">&laquo;</span></a></li>&#39;)
    else:
        # 不是第一页,就加一个上一页的标签
        html_str_list.append(&#39;<li><a href="/book/?page={}"><span aria-hidden="true">&laquo;</span></a></li>&#39;.format(page_num - 1))

    for i in range(page_start, page_end + 1):
        # 如果是当前页就加一个active样式类
        if i == page_num:
            tmp = &#39;<li class="active"><a href="/book/?page={0}">{0}</a></li>&#39;.format(i)
        else:
            tmp = &#39;<li><a href="/book/?page={0}">{0}</a></li>&#39;.format(i)

        html_str_list.append(tmp)

    # 判断,如果是最后一页,就没有下一页
    if page_num >= total_page:
        html_str_list.append(&#39;<li class="disabled"><a href="#"><span aria-hidden="true">&raquo;</span></a></li>&#39;)
    else:
        # 不是最后一页, 就加一个下一页标签
        html_str_list.append(&#39;<li><a href="/book/?page={}"><span aria-hidden="true">&raquo;</span></a></li>&#39;.format(page_num + 1))

    # 加上尾页
    html_str_list.append(&#39;<li><a href="/book/?page={}">尾页</a></li>&#39;.format(total_page))

    page_html = "".join(html_str_list)
    return render(request, "book.html", {"all_book":all_book, "page_html":page_html})

book.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>书籍列表</title>
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
</head>
<body>
<div>
<table class="table table-bordered">
    <thead>
        <tr>
            <th>序列号</th>
            <th>ID值</th>
            <th>书名</th>
            <th>时间</th>
        </tr>
        {% for book in all_book %}
        <tr>
            <td>{{ forloop.counter }}</td>
            <td>{{ book.id }}</td>
            <td>{{ book.name }}</td>
            <td>{{ book.date }}</td>
        </tr>
        {% endfor %}
    </thead>
</table>
<nav aria-label="Page navigation">
  <ul>
      {{ page_html|safe }}
  </ul>
</nav>
</div>
</body>
</html>

book.html

Encapsulated and saved version

class Page(object):
    def __init__(self, page_num, total_count, url_prefix, per_page=10, max_page=11):
        """
        :param page_num: 当前页码数
        :param total_count: 数据总数
        :param url_prefix: a标签href的前缀
        :param per_page: 每页显示多少条数据
        :param max_page: 页面上最多显示几个页码
        """
        self.url_prefix = url_prefix
        self.max_page = max_page
        # 总共需要多少页码来展示
        total_page, m = divmod(total_count, per_page)
        if m:
            total_page += 1
        self.total_page = total_page

        try:
            # 将取出的page转换为int类型
            page_num = int(page_num)
        except Exception as e:
            # 当输入的页码不是正经数字的时候 默认返回第一页的数据
            page_num = 1
        # 如果输入的页码数超过了最大的页码数,默认返回最后一页
        if page_num > total_page:
            page_num = total_page
        self.page_num = page_num

        # 定义两个变量保存数据从哪儿取到哪儿
        self.data_start = (page_num - 1) * 10
        self.data_end = page_num * 10

        # 页面上总共展示多少页码
        if total_page < self.max_page:
            self.max_page = total_page

        half_max_page = self.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 = self.max_page
        # 如果 当前页 加 一半 比总页码数还大, 不然页面上会显示比总页码还大的多余页码
        if page_end >= total_page:
            page_end = total_page
            page_start = total_page - self.max_page + 1
        self.page_start = page_start
        self.page_end = page_end

    @property
    def start(self):
        return self.data_start

    @property
    def end(self):
        return self.data_end

    def page_html(self):
        # 自己拼接分页的HTML代码
        html_str_list = []
        # # 加上首页
        html_str_list.append(&#39;<li><a href="{}?page=1">首页</a></li>&#39;.format(self.url_prefix))
        # 断一下 如果是第一页,就没有上一页
        if self.page_num <= 1:
            html_str_list.append(&#39;<li class="disabled"><a href="#"><span aria-hidden="true">&laquo;</span></a></li>&#39;)
        else:
            # 不是第一页,就加一个上一页的标签
            html_str_list.append(&#39;<li><a href="{}?page={}"><span aria-hidden="true">&laquo;</span></a></li>&#39;.format(self.url_prefix, self.page_num - 1))

        for i in range(self.page_start, self.page_end + 1):
            # 如果是当前页就加一个active样式类
            if i == self.page_num:
                tmp = &#39;<li class="active"><a href="{0}?page={1}">{1}</a></li>&#39;.format(self.url_prefix, i)
            else:
                tmp = &#39;<li><a href="{0}?page={1}">{1}</a></li>&#39;.format(self.url_prefix, i)

            html_str_list.append(tmp)

        # 判断,如果是最后一页,就没有下一页
        if self.page_num >= self.total_page:
            html_str_list.append(&#39;<li class="disabled"><a href="#"><span aria-hidden="true">&raquo;</span></a></li>&#39;)
        else:
            # 不是最后一页, 就加一个下一页标签
            html_str_list.append(&#39;<li><a href="{}?page={}"><span aria-hidden="true">&raquo;</span></a></li>&#39;.format(self.url_prefix, self.page_num + 1))

        # 加上尾页
        html_str_list.append(&#39;<li><a href="{}?page={}">尾页</a></li>&#39;.format(self.url_prefix, self.total_page))

        page_html = "".join(html_str_list)
        return page_html

Guide to using the encapsulated version

def publisher(request):
    page_num = request.GET.get("page")
    total_count = models.Publisher.objects.all().count()
    # 调用封装的Page类,传入相应的参数
    page_obj = Page(page_num, total_count, url_prefix="/publisher/", per_page=10, max_page=11)
    all_publisher = models.Publisher.objects.all()[page_obj.start:page_obj.end]
    page_html = page_obj.page_html()
    return render(request, "publisher.html", {"publisher": all_publisher, "page_html": page_html})

HTML reference corresponding to the encapsulated version

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>图书列表</title>
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
</head>
<body>
<div>
    <table class="table table-bordered">
        <thead>
        <tr>
            <td>序列号</td>
            <td>ID值</td>
            <td>出版社</td>
            <td>时间</td>
        </tr>
        </thead>
        <tbody>
        {% for pub in publisher %}
            <tr>
                <th>{{ forloop.counter }}</th>
                <th>{{ pub.id }}</th>
                <th>{{ pub.name }}</th>
                <th>{{ pub.date }}</th>
            </tr>
        {% endfor %}
        </tbody>
    </table>
    <nav aria-label="Page navigation">
        <ul>
            {{ page_html|safe }}
        </ul>
    </nav>
</div>
</body>
</html>

封装版对应的HTML参考

The rendering is as follows:

The above is the detailed content of Implementation code of Django custom paging in python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.