二十. Django分页 和自定义分页

一. Django分页和自定义分页

1.自定义分页

封装好了的可以直接使用

class Page():
    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_num = int(page_num)
            # 如果输入的页码数超过了最大的页码数,默认返回最后一页
            if page_num > total_page:
                page_num = total_page
        except Exception as e:
            # 当输入的页码不是正经数字的时候 默认返回第一页的数据
            page_num = 1
        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('<li><a href="{}?page=1">首页</a></li>'.format( self.url_prefix))

        # 判断一下 如果是第一页,就没有上一页
        if self.page_num <= 1:
            html_str_list.append('<li class="disabled"><a href="#"><span aria-hidden="true">&laquo;</span></a></li>'.format(self.page_num-1))
        else:
            # 加一个上一页的标签
            html_str_list.append('<li><a href="{}?page={}"><span aria-hidden="true">&laquo;</span></a></li>'.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 = '<li class="active"><a href="{0}?page={1}">{1}</a></li>'.format(self.url_prefix, i)
            else:
                tmp = '<li><a href="{0}?page={1}">{1}</a></li>'.format( self.url_prefix, i)

            html_str_list.append(tmp)

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

        page_html = "".join(html_str_list)
        return page_html
views

from django.shortcuts import render
# Create your views here.
from app01 import models


def books(request):
    # 从URL取参数
    page_num = request.GET.get("page")
    print(page_num, type(page_num))
    # 总数据是多少
    total_count = models.Book.objects.all().count()
    # 调用一个类
    from utils.mypage import Page
    page_obj = Page(page_num, total_count, per_page=10, url_prefix="/books/", max_page=9,)

    ret = models.Book.objects.all()[page_obj.start:page_obj.end]

    page_html = page_obj.page_html()

    return render(request, "books.html", {"books": ret, "page_html": page_html})



def depts(request):
    # 从URL取参数
    page_num = request.GET.get("page")
    print(page_num, type(page_num))
    # 总数据是多少
    total_count = models.Dept.objects.all().count()
    from utils.mypage import Page
    page_obj = Page(page_num, total_count, per_page=10, url_prefix="/depts/", max_page=11, )

    ret = models.Dept.objects.all()[page_obj.start:page_obj.end]
    print(ret)
    page_html = page_obj.page_html()
    return render(request, "dept.html", {"depts": ret, "page_html": page_html})
html模板
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>书籍列表</title>
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
</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>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>部门列表</title>
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
</head>
<body>

<div class="container">
    <table class="table table-bordered">
      <thead>
        <tr>
            <th>序号</th>
            <th>id</th>
            <th>部门名</th>
        </tr>
      </thead>
        <tbody>
        {% for dept in depts %}
            <tr>
            <td>{{ forloop.counter }}</td>
            <td>{{ dept.id }}</td>
            <td>{{ dept.name }}</td>
            </tr>
        {% endfor %}

        </tbody>
</table>
<nav aria-label="Page navigation">
  <ul class="pagination">
        {{ page_html|safe }}
  </ul>
</nav>
</div>
</body>
</html>
models

from django.db import models

# Create your models here.


class Employee(models.Model):
    name = models.CharField(max_length=16)
    age = models.IntegerField()
    salary = models.IntegerField()
    province = models.CharField(max_length=32)
    dept = models.CharField(max_length=16)

    def __str__(self):
        return self.name

    class Meta:
        db_table = "employee"


class Employee2(models.Model):
    name = models.CharField(max_length=16)
    age = models.IntegerField()
    salary = models.IntegerField()
    province = models.CharField(max_length=32)
    dept = models.ForeignKey(to="Dept")

    def __str__(self):
        return self.name

    class Meta:
        db_table = "employee2"


class Dept(models.Model):
    name = models.CharField(max_length=16, unique=True)

    def __str__(self):
        return self.name


    class Meta:
        db_table = "dept2"



class Author(models.Model):
    name = models.CharField(max_length=32)
    books = models.ManyToManyField(to="Book")

    def __str__(self):
        return self.name

    class Meta:
        db_table = "author"


class Book(models.Model):
    title = models.CharField(max_length=32)

    def __str__(self):
        return self.title

    class Meta:
        db_table = "book"
urls

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),

    url(r'^books/$', views.books),
    url(r'^depts/$', views.depts),
]

2.django自带分页

from django.shortcuts import render,HttpResponse
# 启动服务器
# D:\04learnpython\01Web_Djang\webpython>python manage.py runserver


# 传统分页
USER_LIST=[]
for i in range(1,999):
    temp={"name":"root"+str(i),"age":i}
    USER_LIST.append(temp)
# http://127.0.0.1:8000/myapp/get/?p=6
def get(request):
      per_page_count=10    # 每页显示十条数据

      current_page=request.GET.get("p")
      current_page=int(current_page)

      strt=(current_page-1)*per_page_count  #起始位置
      end=current_page*per_page_count       #结束位置

      data=USER_LIST[strt:end]  # 截取
      # return HttpResponse("欢迎老到djiango的页面啊哈哈哈哈哈")
      prev_page=current_page-1
      next_page=current_page+1
      return render(request,"html_app/01.html",{"user":data,"aa":prev_page,"bb": next_page})
 

# django的分页
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def geta(request):
  # Paginator(USER_LIST,10) 得出共有多少条数据
  # per_page: 每页显示条目数量
  # connt   : 数据总个数
  # num_pages:总页数
  # page_range:总页数的索引范围 如: (1,10),(1,200)
  # page : page对象   (是否有下一页或者是否有上一页)
   # Paginator对象
   current_page=request.GET.get("a")
   paginator=Paginator(USER_LIST,10)
   try:
      # page对象
      posts=paginator.page(current_page)
      # has_next  是否有下一页
      # next_page_number  下一页页码
      # has_previous   是否有上一页
      # previous_page_number  上一页页码
      # object_list     分页之后的数据列表
      # number     当前页
      # pageinator   Paginator 对象
   except PageNotAnInteger:
     posts=paginator.page(1)
   except EmptyPage:
     posts=paginator.page(pageinator.num_pages)
   return render(request,"html_app/02.html",{"user":posts})


# django的分页功能化
def gets(request):
   current_page=request.GET.get("c")
   paginator=Paginator(USER_LIST,10)
   try:
      posts=paginator.page(current_page)
   except PageNotAnInteger:
     posts=paginator.page(1)
   except EmptyPage:
     posts=paginator.page(pageinator.num_pages)
   return render(request,"html_app/03.html",{"user":posts})
HTML模板
01.html

<!DOCTYPE html>
<html>
    <head>

         {%load staticfiles%}
        <meta charset="UTF-8">
        <title>111</title>
        <!-- <script type="text/javascript" src="/static/webpage/js/jquery1.js" ></script> -->
         <!-- 引用静态的方式-->
        <script type="text/javascript" src="{%static 'webpage/js/jquery1.js'%}" ></script>  
        
    </head>
    <body>
   <ul>
     {%for row in user %}
         <li>{{row.name}}----{{row.age}}</li>
     {%endfor%}
   </ul>
   <a href="/myapp/get/?p={{aa}}">上一页</a>
   <a href="/myapp/get/?p={{bb}}">下一页</a>
    </body>
</html>
02 .html

<!DOCTYPE html>
<html>
    <head>

         {%load staticfiles%}
        <meta charset="UTF-8">
        <title>111</title>
        <!-- <script type="text/javascript" src="/static/webpage/js/jquery1.js" ></script> -->
         <!-- 引用静态的方式-->
        <script type="text/javascript" src="{%static 'webpage/js/jquery1.js'%}" ></script>  
        
    </head>
    <body>
哈哈哈哈哈!!!!!!!!!!!!!!!!!!!!!!!!11
   <ul>
     {%for row in user.object_list %}
         <li>{{row.name}}----{{row.age}}</li>

     {%endfor%}
   </ul>
      {%include "html_page/pager.html" %}
    </body>
</html>
03.html

<!DOCTYPE html> <html> <head> {%load staticfiles%} <meta charset="UTF-8"> <title>111</title> <!-- <script type="text/javascript" src="/static/webpage/js/jquery1.js" ></script> --> <!-- 引用静态的方式--> <script type="text/javascript" src="{%static 'webpage/js/jquery1.js'%}" ></script> </head> <body> 拉拉拉啊啦啦 <ul> {%for row in user.object_list %} <li>{{row.name}}----{{row.age}}</li> {%endfor%} </ul> {%if user.has_previous %} <a href="/myapp/gets/?c={{user.previous_page_number}}">上一页</a> {%else%} <a href="#">上一页</a> {%endif%} {% if user.has_next %} <a href="/myapp/gets?c={{user.next_page_number}}">下一页</a> {%endif%} <span> <!-- 当前页 --> 当前页 {{user.number}} <!-- 总页 数--> /{{user.paginator.num_pages}}总页数 </span> </body> </html>
urls

from django.conf.urls import url,include
from django.contrib import admin
from.import views

urlpatterns = [

   # 班级
    url(r'^get/',views.get),
    url(r'^geta/',views.geta), 
    url(r'^gets/',views.gets),  
   

]

 

转载于:https://www.cnblogs.com/lovershowtime/p/11370749.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值