需要安装个库叫django-pure-pagination,直接pip,在github上可以查看文档。在后台views.py里实现分页,再传到前端。
先在installed_apps里加入 'pure_pagination'
views.py
from django.shortcuts import render
from django.views.generic import View
from django.shortcuts import render_to_response
from pure_pagination import Paginator, EmptyPage, PageNotAnInteger
from .models import CourseOrg, CityDict
# Create your views here.
class OrgView(View):
"""
课程机构列表功能
"""
def get(self, request):
#课程机构
all_orgs = CourseOrg.objects.all()
org_nums = all_orgs.count()
#城市
all_citys = CityDict.objects.all()
#对课程机构分页
try:
page = request.GET.get('page', 1)
except PageNotAnInteger:
page = 1
p = Paginator(all_orgs, 5, request=request,)
orgs = p.page(page)
return render(request, "org-list.html", {
"all_orgs":orgs,
"all_citys":all_citys,
"org_nums":org_nums
})
p = Paginator(all_orgs, 5, request=request,)里的5是指一页显示几个,官方文档没写,但没写会报错。这里要把all_orgs分页显示,于是p = Paginator(all_orgs, 5, request=request,)。
前端页码部分:
<div class="pageturn">
<ul class="pagelist">
{% if all_orgs.has_previous %}
<li class="long"><a href="?{{ all_orgs.previous_page_number.querystring }}">上一页</a></li>
{% endif %}
{% for page in all_orgs.pages %}
{% if page %}
{% ifequal page all_orgs.number %}
<li class="active"><a href="?page=1">{{ page }}</a></li>
{% else %}
<li><a href="?{{ page.querystring }}" class="page">{{ page }}</a></li>
{% endifequal %}
{% else %}
<li class="none"><a href="">...</a></li>
{% endif %}
{% endfor %}
{% if all_orgs.has_next %}
<li class="long"><a href="?{{ all_orgs.next_page_number.querystring }}">下一页</a></li>
{% endif %}
</ul>
</div>
</div>
</div>
逻辑是如果当前页有前一页则显示“上一页”三个字的超链接。对于每一页,如果当前页存在,判断页码部分显示的页码是否等于当前页码,把等于的页码active,不等于的不active,但也显示。如果当前页不存在则显示...。如果当前页有下一页则显示“下一页”
网友评论