1. 安装
pip install django-pure-pagination
2. 添加入setting中的INSTALLED_APPS中
INSTALLED_APPS = [
'pure_pagination',
]
3. 配置默认参数
PAGINATION_SETTINGS = {
'PAGE_RANGE_DISPLAYED': 10,
# 显示当前页面的相邻的页面数
'MARGIN_PAGES_DISPLAYED': 2,
# 显示的第一页和最后一页相邻的页数
'SHOW_FIRST_PAGE_WHEN_INVALID': True,
# 无效页面时,显示第一页而不是404页面
}
4. view代码
from django.shortcuts import render
from django.views.generic import View
from pure_pagination import Paginator, PageNotAnInteger
from .models import CourseOrg, CityDict
class OrgView(View):
def get(self, request):
all_orgs = CourseOrg.objects.all()
# 对课程机构进行分页
# 尝试获取前台get请求传递过来的page参数
# 如果是不合法的配置参数默认返回第一页
try:
page = request.GET.get('page', 1)
except PageNotAnInteger:
page = 1
# 将需要分页的数据传入Paginator中, 并指定分页的数量
p = Paginator(all_orgs, 5, request=request)
orgs = p.page(page)
return render(request, 'org-list.html', locals())
5. 前端使用
{% for all_org in orgs.object_list %}
<dl class="des difdes">
<dt>
<a href="org-detail-homepage.html">
<img width="200" height="120" class="scrollLoading"
data-url="{{ MEDIA_URL }}{{ all_org.image }}"/>
</a>
</dt>
<dd>
<div class="clearfix">
<a href="org-detail-homepage.html">
<h1>{{ all_org.name }}</h1>
<div class="pic fl">
<img src="{% static 'images/authentication.png' %}"/>
<img src="{% static 'images/gold.png' %}"/>
</div>
</a>
</div>
<ul class="cont">
<li class="first"><p class="pic9">课程数:<span>1</span></p>
<p class="c7">学习人数:<span>1000</span></p></li>
<li class="c8" style="padding-left:18px;">北京市海淀区中关村北大街</li>
<li class="pic10" style="padding-left:18px;">经典课程:
<a href="/diary/19/">c语言基础入门</a>
<a href="/diary/16/">数据库基础</a>
</li>
</ul>
</dd>
<div class="buy start_groupbuy jsShowPerfect2" data-id="22"><br/>联系<br/>服务</div>
</dl>
{% endfor %}
6. 前端分页
<div class="pageturn">
<ul class="pagelist">
{% if orgs.has_previous %}
<li class="long"><a href="?{{ orgs.previous_page_number.querystring }}">上一页</a></li>
{% endif %}
{% for page in orgs.pages %}
{% if page %}
{% ifequal page orgs.number %}
<li class="active"><a href="?{{ page.querystring }}">{{ 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 orgs.has_next %}
<li class="long"><a href="?{{ orgs.next_page_number.querystring }}">下一页</a></li>
{% endif %}
</ul>
</div>