Django学生管理-翻页设置

前期准备

  1. 设置展示页数和每页展示的行数,这里用page_no和page_size表示
page_no = int(request.GET.get('page_no',1))  #页id
page_size =int(request.GET.get('page_size',3))    #页内行数
  1. 查询范围,这里用start_index和end_index表示
 start_index = (page_no-1)* page_size   #开始索引
 end_index = page_no*page_size     #结束索引
  1. 获取数据库总对象和页数,页数表
 rows_amount = Student.objects.all().count()    #获取对象总行数
 page_amount = rows_amount//page_size+1    #总共的页数=总行数除每页行数取整加一页
 page_amount_list = [i for i in range(page_amount)]  #[1,2,3]   总共的页数列表

根据范围取出后台数据

res = Student.objects.all().order_by('no')[start_index:end_index]  
 #从[start_index:end_index]范围内取得学生对象
    text = {
        'res':res, # 键名是在模板当中使用的
        'page_amount_list':page_amount_list,  #页数列表[1,2,3]
        'page_no':page_no,     #页id
        'page_previous':page_no-1,     #上一页,页id-1
        'page_next':page_no+1            #下一页,页id+1
    }

    return render(request,'student/index.html',text)   #将数据传到前台

进入index.html页面后
局部理解:
#鼠标点击上一页时,根据后台计算改值跳转到改地址。

<li class="page-item"><a href="/student/select/?page_no={{page_previous}}&page_size=3" class="page-link">上一页</a></li>

{# 高亮设置,如果此时id等于页id,显示高亮 #}

<li {% if forloop.counter == page_no %} 
                    class="page-item active"
                    {% else %}				 
                    class="page-item">
                    {% endif %}
                    

#循环页数列表,将信息添加并跳转到指定页面。

{% for i in page_amount_list %}    {# 循环页数列表,将信息添加 #}
      <li>
      <a href="/student/select/?page_no={{ forloop.counter }}&page_size=3"class="page-link">{{ forloop.counter }}</a> 
     </li>
{% endfor %}

最后在浏览器打开就ok了
http://127.0.0.1:8000/student/select/
全局代码展示
前台代码
在这里插入图片描述
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190716194742872.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1dYQl9nZWdl,size_16,color_FFFFFF,t_70
后台代码
在这里插入图片描述
网页展示
在这里插入图片描述

发布了4 篇原创文章 · 获赞 3 · 访问量 194

猜你喜欢

转载自blog.csdn.net/WXB_gege/article/details/96171319