第三方分页模块: django-pure-pagination 是基于django的pagination做的一款更好用的分页器
安装
pip install django-pure-pagination
添加pure_pagination app
settings.pyINSTALLED_APPS = [ ... 'users', 'pure_pagination', ]
urls.py
from users import views
urlpatterns = [
path('', views.index, name="index"),
path('admin/', admin.site.urls),
]
views.py
from pure_pagination import Paginator, EmptyPage, PageNotAnInteger
def index(request):
try:
page = request.GET.get('page', 1)
except PageNotAnInteger:
page = 1
# 要返回的所有数据
objects = ['john', 'edward', 'josh', 'frank','john', 'edward', 'josh', 'frank','john', 'edward', 'josh', 'frank']
# 分页器分页后的数据返回,Provide Paginator with the request object for complete querystring generation
p = Paginator(objects, 5, request=request)
people = p.page(page)
return render(request, 'index.html', {"poeple": people})
index.html
{% for p in poeple.object_list %}
<div>
First name: {{ p }}
</div>
{% endfor %}
{# The following renders the pagination html #}
<div id="pagination">
{{ poeple.render }} {# 渲染页码 #}
</div>
<div id="pagination">
{{ poeple.render }} {# 渲染页码 #}
</div>
渲染成html为
<div class="pagination">
<span class="disabled prev">‹‹ previous</span>
<span class="current page">1</span>
<a href="?page=2" class="page">2</a>
<a href="?page=3" class="page">3</a>
<a href="?page=2" class="next">next ››</a>
</div>