Django如何在views视图中做分页

Posted forsaken627

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django如何在views视图中做分页相关的知识,希望对你有一定的参考价值。

场景模拟

class Teacher(models.Model):
    name = models.CharField(max_length=32)


class UserInfo(models.Model):
    username = models.CharField(max_length=32)
    QQ = models.CharField(max_length=16)
    class_name = models.CharField(max_length=32)
    c_time = models.DateTimeField(auto_now_add=True)
    status = models.IntegerField()
    teacher = models.ForeignKey(Teacher)

1.urls.py

url(r'^index/', views.index),

2.views.py

def page_list_return(total, current=1):
    """
    page
    分页,返回本次分页的最小页数到最大页数列表
    """
    min_page = current - 2 if current - 4 > 0 else 1
    max_page = min_page + 4 if min_page + 4 < total else total

    return range(min_page, max_page + 1)


def pages(post_objects, request):
    """
    分页公用函数,返回分页的对象元组
    """
    paginator = Paginator(post_objects, 3)
    try:
        current_page = int(request.GET.get('page', '1'))
    except ValueError:
        current_page = 1

    page_range = page_list_return(len(paginator.page_range), current_page)

    try:
        page_objects = paginator.page(current_page)
    except (EmptyPage, InvalidPage):
        page_objects = paginator.page(paginator.num_pages)

    if current_page >= 5:
        show_first = 1
    else:
        show_first = 0

    if current_page <= (len(paginator.page_range) - 3):
        show_end = 1
    else:
        show_end = 0

        # 所有对象,分页器,本页对象,所有页码,本页页码,是否显示第一页,是否显示最后一页
    return post_objects, paginator, page_objects, page_range, current_page, show_first, show_end


def index(request):
    '''

    :param request:
    :return:
    '''
    if request.method == "GET":
        queryset = models.UserInfo.objects.all().order_by('id')
        post_objects, paginator, page_objects, page_range, current_page, show_first, show_end = pages(queryset, request)
        return render(request, 'index.html', locals())

实现

  • index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/static/bootstrap.min.css">
    <title>Title</title>
    <style>
        .ibox-content {
            background-color: #ffffff;
            color: inherit;
            padding: 15px 20px 20px 20px;
            border-color: #e7eaec;
            border-image: none;
            border-style: solid solid none;
            border-width: 1px 0;
        }
    </style>
</head>
<body>
<div class="wrapper">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5> 概览 </h5>
                </div>
                <div class="ibox-content" >
                    <div class="">
                        <a class="btn btn-sm btn-primary add_vendor"> 添加 </a>
                        <a class="btn btn-sm btn-warning "> 添加 </a>
                        <form id="search_form" method="get" action="" class="pull-right mail-search">
                        </form>
                    </div>
                    <table class="table table-striped table-bordered table-hover " id="editable" style="margin-top: 10px">
                        <thead>
                        <tr>
                            <th class="text-center">序号</th>
                            <th class="text-center">姓名</th>
                            <th class="text-center">QQ号码</th>
                            <th class="text-center">班级</th>
                            <th class="text-center">时间</th>
                            <th class="text-center">状态</th>
                            <th class="text-center">班主任</th>
                            <th class="text-center">操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for item in page_objects %}
                            <tr class="gradeX">
                                <td style="display: none">{{ item.map_id }}</td>
                                <td>{{ forloop.counter }}</td>
                                <td>{{ item.username }}</td>
                                <td>{{ item.QQ }}</td>
                                <td>{{ item.class_name }}</td>
                                <td>{{ item.c_time|date:"Y-m-d" }}</td>
                                <td>{{ item.status }}</td>
                                <td>{{ item.teacher.name }}</td>

                                <td class="text-center">
                                    <a href="" class="btn btn-xs btn-info">编辑</a>
                                    <button type="button" class="btn btn-xs btn-danger del_item">删除</button>
                                </td>
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                    <div class="row">
                        <div class="col-sm-6">
                            <div class="dataTables_info" id="editable_info" role="status" aria-live="polite">
                                第 {{ page_objects.start_index }} ~ {{ page_objects.end_index }}条 |
                                总 {{ paginator.count }} 条
                            </div>
                        </div>
                        {% include 'pagintor.html' %}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>
  • pagintor.html
<div class="col-sm-6">
    <div class="dataTables_paginate paging_simple_numbers" id="editable_paginate">
        <ul class="pagination" style="margin-top: 0; float: right">
            {% if page_objects.has_previous %}
                <li class="paginate_button previous" aria-controls="editable" tabindex="0" id="editable_previous">
                    <a class="page" href="?page={{ page_objects.previous_page_number }}">Previous</a>
                </li>
            {% else %}
                <li class="paginate_button previous disabled" aria-controls="editable" tabindex="0" id="editable_previous">
                     <a class="page" href="#">Previous</a>
                </li>
            {% endif %}
            {% ifequal show_first 1 %}
                <li class="paginate_button" aria-controls="editable" tabindex="0"><a class="page" href="?page=1"  title="第1页">1...</a></li>
            {% endifequal %}
            {% for page in page_range %}
                {% ifequal current_page page %}
                    <li class="paginate_button active"  aria-controls="editable" tabindex="0"><a class="page" href="?page={{ page }}"  title="第{{ page }}页">{{ page }}</a></li>
                {% else %}
                    <li class="paginate_button" aria-controls="editable" tabindex="0"><a class="page" href="?page={{ page }}"  title="第{{ page }}页">{{ page }}</a></li>
                {% endifequal %}
            {% endfor %}
            {% ifequal show_end 1 %}
                <li class="paginate_button" aria-controls="editable" tabindex="0"><a class="page" href="?page={{ p.num_pages }}"  title="第{{ page }}页">...{{ p.num_pages }}</a></li>
            {% endifequal %}
            {% if page_objects.has_next %}
                <li class="paginate_button next" aria-controls="editable" tabindex="0" id="editable_next">
                    <a class="page" href="?page={{ page_objects.next_page_number }}">Next</a>
                </li>
            {% else %}
                <li class="paginate_button next disabled" aria-controls="editable" tabindex="0" id="editable_next">
                    <a class="page" href="#">Next</a>
                </li>
            {% endif %}
        </ul>
    </div>
</div>

效果

技术图片

语法举例

import os
 
from django.core.paginator import Paginator
objects = ['john','paul','george','ringo','lucy','meiry','checy','wind','flow','rain']<br>
p = Paginator(objects,3)  # 3条数据为一页,实例化分页对象
print p.count  # 10 对象总共10个元素
print p.num_pages  # 4 对象可分4页
print p.page_range  # xrange(1, 5) 对象页的可迭代范围
 
page1 = p.page(1)  # 取对象的第一分页对象
print page1.object_list  # 第一分页对象的元素列表['john', 'paul', 'george']
print page1.number  # 第一分页对象的当前页值 1
 
page2 = p.page(2)  # 取对象的第二分页对象
print page2.object_list  # 第二分页对象的元素列表 ['ringo', 'lucy', 'meiry']
print page2.number  # 第二分页对象的当前页码值 2
 
print page1.has_previous()  # 第一分页对象是否有前一页 False
print page1.has_other_pages()  # 第一分页对象是否有其它页 True
 
print page2.has_previous()  # 第二分页对象是否有前一页 True
print page2.has_next()  # 第二分页对象是否有下一页 True
print page2.next_page_number()  # 第二分页对象下一页码的值 3
print page2.previous_page_number()  # 第二分页对象的上一页码值 1
print page2.start_index()  # 第二分页对象的元素开始索引 4
print page2.end_index()  # 第2分页对象的元素结束索引 6

以上是关于Django如何在views视图中做分页的主要内容,如果未能解决你的问题,请参考以下文章

Django实现自定义分页

django 做了搜索之后再做分页 结果显示第一页是正常的 但是按下一页后显示出整个主页的第二页

Django的分页和中间件

Django-前端分页效果

当我在基于类的视图中应用过滤器时,如何在 django 中使用分页分页。网址总是不断变化我如何跟踪网址

quartz怎么做分页查询