Django|Django Paginator分页器的使用示例
# name: models.pyfrom django.db import modelsclass User(models.Model):id = models.AutoField(primary_key=True)username = models.CharField(max_length=32)password = models.CharField(max_length=32)# 插入测试数据import randomdef index(request):for i in range(1,100):chars = []pasd = []for x in range(1,8):chars.append(random.choice('abcdefghijklmnopqrstuvwxyz'))pasd.append(random.choice('0987654321'))user = "".join(chars)pwd = "".join(pasd)models.User.objects.create(username=user, password=pwd)return HttpResponse("ok")
Title - 锐客网 统计: {{ currentPage }}/{{ paginator.num_pages }} 共查询到:{{ paginator.count }} 条数据 页码列表:{{ paginator.page_range }}
{% for article in user_list %} 序号 用户名 用户密码 {% endfor %} {{ article.id }} {{ article.username }} {{ article.password }}
# name: views.pyfrom django.shortcuts import render,HttpResponsefrom MyWeb import modelsfrom django.core.paginator import Paginator, EmptyPage, PageNotAnIntegerdef page(request):user = models.User.objects.all()paginator = Paginator(user, 10)currentPage = int(request.GET.get("id",1))try:user_list = paginator.page(currentPage)except PageNotAnInteger:user_list = paginator.page(1)except:user_list = paginator.page(paginator.num_pages)return render(request,"page.html",{"user_list":user_list,"paginator":paginator,"currentPage":currentPage})
# name: urls.pyfrom MyWeb import viewsurlpatterns = [path('admin/', admin.site.urls),path('page',views.page)]
文章图片
上方的分页代码还有一个不足之处,当我们的页码数量过多时,会全部展示出来,整个页面都是很不美观,我们直接在上方代码上稍加修改一下试试.
# name: views.pyfrom django.shortcuts import render,HttpResponsefrom MyWeb import modelsfrom django.core.paginator import Paginator, EmptyPage, PageNotAnIntegerdef page(request):user = models.User.objects.all()paginator = Paginator(user, 10)currentPage = int(request.GET.get("id",1))if paginator.num_pages > 15:if currentPage-5 < 1:pageRange = range(1,11)elif currentPage+5 > paginator.num_pages:pageRange = range(currentPage-5,paginator.num_pages)else:pageRange = range(currentPage-5,currentPage+5)else:pageRange = paginator.page_rangetry:user_list = paginator.page(currentPage)except PageNotAnInteger:user_list = paginator.page(1)except:user_list = paginator.page(paginator.num_pages)return render(request,"page.html",{"user_list":user_list,"paginator":paginator,"page_range":pageRange,# 此处自定义一个分页段"currentPage":currentPage})
前端分页代码只需要将paginator.page_range改为page_range其他地方不需要动.
{% for item in page_range %}{% if item == currentPage %}{{ item }} {% else %}{{ item }} {% endif %}{% endfor %}
【Django|Django Paginator分页器的使用示例】这样,无论有多少页面,都能够保证只显示10页。
分页后添加删除功能
1.删除功能的实现,很简单,只需要定位得到指定的tr上,取出里面的id号码,并发送给后端,执行sql删除就完事了。
Title - 锐客网 .................
{% for article in user_list %} 选择 序号 用户名 用户密码 {% endfor %} {{ article.id }} {{ article.username }} {{ article.password }}
文章图片
实现模态框编辑内容
点击选中行,然后弹出模态框,并自动的获取到该行数据,编辑好以后直接用ajax发送post请求到后端处理即可。
编辑模式
选择 用户ID 用户名称 用户邮箱 1001 lyshark lyshark@123.com 1002 搞事情 lyshark@123.com
文章图片
完整代码笔记
利用BootStrap框架实现分页: 通过使用bootstrap框架,并配合Django自带的分页组件即可实现简单的分页效果.
# name: models.pyfrom django.db import modelsclass User(models.Model):id = models.AutoField(primary_key=True)username = models.CharField(max_length=32)password = models.CharField(max_length=32)# 插入测试数据import randomdef index(request):for i in range(1,1000):chars = []pasd = []for x in range(1,8):chars.append(random.choice('abcdefghijklmnopqrstuvwxyz'))pasd.append(random.choice('0987654321'))user = "".join(chars)pwd = "".join(pasd)models.User.objects.create(username=user, password=pwd)return HttpResponse("ok")
Title - 锐客网 统计: {{ currentPage }}/{{ paginator.num_pages }} 共查询到:{{ paginator.count }} 条数据 页码列表:{{ paginator.page_range }}
{% for article in user_list %} 序号 用户名 用户密码 {% endfor %} {{ article.id }} {{ article.username }} {{ article.password }}
# name: views.pyfrom django.shortcuts import render,HttpResponsefrom MyWeb import modelsfrom django.core.paginator import Paginator, EmptyPage, PageNotAnIntegerdef page(request):user = models.User.objects.all()paginator = Paginator(user, 10)currentPage = int(request.GET.get("id",1))try:user_list = paginator.page(currentPage)except PageNotAnInteger:user_list = paginator.page(1)except:user_list = paginator.page(paginator.num_pages)return render(request,"page.html",{"user_list":user_list,"paginator":paginator,"currentPage":currentPage})
# name: urls.pyfrom MyWeb import viewsurlpatterns = [path('admin/', admin.site.urls),path('page',views.page)]
上方的分页代码还有一个不足之处,当我们页面中的页码数量过多时,默认会将页码全部展示出来,整个页面看上去很不美观,我们可以直接在上方分页代码上稍加修改即可,如下代码.
# name: views.pyfrom django.shortcuts import render,HttpResponsefrom MyWeb import modelsfrom django.core.paginator import Paginator, EmptyPage, PageNotAnIntegerdef page(request):user = models.User.objects.all()paginator = Paginator(user, 10)currentPage = int(request.GET.get("id",1))if paginator.num_pages > 15:if currentPage-5 < 1:pageRange = range(1,11)elif currentPage+5 > paginator.num_pages:pageRange = range(currentPage-5,paginator.num_pages)else:pageRange = range(currentPage-5,currentPage+5)else:pageRange = paginator.page_rangetry:user_list = paginator.page(currentPage)except PageNotAnInteger:user_list = paginator.page(1)except:user_list = paginator.page(paginator.num_pages)return render(request,"page.html",{"user_list":user_list,"paginator":paginator,"page_range":pageRange,# 此处自定义一个分页段"currentPage":currentPage})
前端分页代码只需要将paginator.page_range改为page_range其他地方不需要动.
{% for item in page_range %}{% if item == currentPage %}{{ item }} {% else %}{{ item }} {% endif %}{% endfor %}
利用layui框架实现分页:
layui是一个完整的前端开发框架,利用它可以快速构建分页应用,比BootStrap更加灵活.
# models.pyfrom django.db import modelsclass HostDB(models.Model):id = models.AutoField(primary_key=True)hostname = models.CharField(max_length=64)hostaddr = models.CharField(max_length=64)hostmode = models.CharField(max_length=64)
# views.pyfrom django.shortcuts import render,HttpResponsefrom django.core.paginator import Paginator,EmptyPage,PageNotAnIntegerfrom MyWeb import modelsimport jsondef index(request):return render(request,"index.html")def get_page(request):data = https://www.it610.com/article/models.HostDB.objects.all()dataCount = data.count()pageIndex = request.GET.get("pageIndex")pageSize = request.GET.get("pageSize")print("当前索引:{} 当前大小:{}".format(pageIndex,pageSize))print("所有记录:{} 数据总条数:{}".format(data,dataCount))# 将数据组装成字典后放入data_list列表data_list,ref_data = [],[]for item in data:dict = { 'id':item.id , 'hostname':item.hostname, 'hostaddr':item.hostaddr, 'hostmode':item.hostmode }data_list.append(dict)# 使用分页器分页pageInator = Paginator(data_list,pageSize)context = pageInator.page(pageIndex)for item in context:ref_data.append(item)# 返回分页格式data = https://www.it610.com/article/{"code": 0,"msg": "ok","DataCount": dataCount,"data": ref_data }return HttpResponse(json.dumps(data))
# name: url.pyfrom MyWeb import viewsurlpatterns = [path('admin/', admin.site.urls),path('',views.index),path('get_page/',views.get_page)]
layui实现完整表格分页:
通过使用layui框架完成的一个相对完整的表格分页,可用于生产环境.
# name:views.pyfrom django.shortcuts import render,HttpResponsefrom django.core.paginator import Paginator,EmptyPage,PageNotAnIntegerfrom MyWeb import modelsimport jsondef index(request):return render(request,"index.html")def get_page(request):data = https://www.it610.com/article/models.HostDB.objects.all()dataCount = data.count()pageIndex = request.GET.get("pageIndex")pageSize = request.GET.get("pageSize")print("当前索引:{} 当前大小:{}".format(pageIndex,pageSize))print("所有记录:{} 数据总条数:{}".format(data,dataCount))list = []res = []for item in data:dict = {}dict['id'] = item.iddict['hostname'] = item.hostnamedict['hostaddr'] = item.hostaddrdict['hostmode'] = item.hostmodelist.append(dict)pageInator = Paginator(list,pageSize)context = pageInator.page(pageIndex)for item in context:res.append(item)data = https://www.it610.com/article/{"code": 0,"msg": "ok","DataCount": dataCount,"data": res }return HttpResponse(json.dumps(data))def search_page(request):sql = request.GET.get("hostname")data = models.HostDB.objects.all().filter(hostname=sql)list = []for item in data:dict = {}dict['id'] = item.iddict['hostname'] = item.hostnamedict['hostaddr'] = item.hostaddrdict['hostmode'] = item.hostmodelist.append(dict)data = https://www.it610.com/article/{"code": 0,"msg": "ok","DataCount": 1,"data": list }return HttpResponse(json.dumps(data))def delete_page(request):get_id = request.GET.get("id")models.HostDB.objects.filter(id=get_id).delete()return render(request,"index.html")def update_page(request):get_id = request.GET.get("id")get_hostname = request.GET.get("hostname")get_hostaddr = request.GET.get("hostaddr")get_hostmode = request.GET.get("hostmode")print(get_hostmode)obj = models.HostDB.objects.get(id=get_id)obj.hostname = get_hostnameobj.hostaddr = get_hostaddrobj.hostmode = get_hostmodeobj.save()return render(request,"index.html")
# name: urls.pyfrom MyWeb import viewsurlpatterns = [path('',views.index),path('get_page/',views.get_page),path('search_page/',views.search_page),path('delete_page/',views.delete_page),path("update_page/",views.update_page)]
自己实现分页:
转载代码,仅用于收藏。
from urllib.parse import urlencodeclass Pagination(object):def __init__(self,current_page,total_count,base_url,params,per_page_count=10,max_pager_count=10):try:current_page = int(current_page)except Exception as e:current_page = 1if current_page <= 1:current_page = 1self.current_page = current_page# 数据总条数self.total_count = total_count# 每页显示10条数据self.per_page_count = per_page_count# 页面上应该显示的最大页码max_page_num, div = divmod(total_count, per_page_count)if div:max_page_num += 1self.max_page_num = max_page_num# 页面上默认显示11个页码(当前页在中间)self.max_pager_count = max_pager_countself.half_max_pager_count = int((max_pager_count - 1) / 2)# URL前缀self.base_url = base_url# request.GETimport copyparams = copy.deepcopy(params)# params._mutable = Trueget_dict = params.to_dict()# 包含当前列表页面所有的搜/索条件self.params = get_dict@propertydef start(self):return (self.current_page - 1) * self.per_page_count@propertydef end(self):return self.current_page * self.per_page_countdef page_html(self):# 如果总页数 <= 11if self.max_page_num <= self.max_pager_count:pager_start = 1pager_end = self.max_page_num# 如果总页数 > 11else:# 如果当前页 <= 5if self.current_page <= self.half_max_pager_count:pager_start = 1pager_end = self.max_pager_countelse:# 当前页 + 5 > 总页码if (self.current_page + self.half_max_pager_count) > self.max_page_num:pager_end = self.max_page_numpager_start = self.max_page_num - self.max_pager_count + 1#倒这数11个else:pager_start = self.current_page - self.half_max_pager_countpager_end = self.current_page + self.half_max_pager_countpage_html_list = []# {source:[2,], status:[2], gender:[2],consultant:[1],page:[1]}# 首页self.params['page'] = 1first_page = '首页' % (self.base_url,urlencode(self.params),)page_html_list.append(first_page)# 上一页self.params["page"] = self.current_page - 1if self.params["page"] <= 1:pervious_page = '上一页' % (self.base_url, urlencode(self.params))else:pervious_page = '上一页' % ( self.base_url, urlencode(self.params))page_html_list.append(pervious_page)# 中间页码for i in range(pager_start, pager_end + 1):self.params['page'] = iif i == self.current_page:temp = '%s' % (self.base_url,urlencode(self.params), i,)else:temp = '%s' % (self.base_url,urlencode(self.params), i,)page_html_list.append(temp)# 下一页self.params["page"] = self.current_page + 1if self.params["page"] > self.max_page_num:self.params["page"] = self.current_pagenext_page = '下一页' % (self.base_url, urlencode(self.params))else:next_page = '下一页' % (self.base_url, urlencode(self.params))page_html_list.append(next_page)# 尾页self.params['page'] = self.max_page_numlast_page = '尾页' % (self.base_url, urlencode(self.params),)page_html_list.append(last_page)return ''.join(page_html_list)
文章出处:https://www.cnblogs.com/lyshark
以上就是Django Paginator分页器的使用示例的详细内容,更多关于Django Paginator分页器的使用的资料请关注脚本之家其它相关文章!
推荐阅读
- django-前后端交互
- django2.2|django2.2 一般项目步骤(初步)
- Mybatis|Mybatis Plus 分页插件
- django|django 自定义.save()方法
- django|django 获取用户的域名
- django开发电子商城(二十二)购物车商品的所有者身份转换
- 关于ajax异步分页传输数据到页面为字符串的JS解决办法
- Django安装mysql
- Django记录操作日志与LogEntry的使用详解
- 1.3Django中创建项目