一. 安装模块
django_pure_pagination
是第三方扩展包, 所以得通过命令来安装
- 打开cmd输入
pip install django_pure_pagination
二. 在settings.py中增加添加分页器
INSTALLED_APPS = [
...
'pure_pagination',
]
三. 分页后可修改页码显示的个数和样式
PAGINATION_SETTINGS = {
'PAGE_RANGE_DISPLAYED': 5,
'MARGIN_PAGES_DISPLAYED': 2,
'SHOW_FIRST_PAGE_WHEN_INVALID': True,
}
四. 视图中的分页
from pure_pagination import Paginator
def index(request):
"""主页"""
current_page = request.GET.get('page', 1)
post_list = Post.objects.all()
paginator = Paginator(post_list, 10)
page_obj = paginator.page(current_page)
context['page_obj'] = page_obj
return render(request, 'blog/index.html', context)
五. 前端页面, 使用bootstrap美化分页
{
<nav style="text-align: center">
<ul class="pagination">
{% if page_obj.has_previous %} {
<li class="previous">
{
<a href="?{{ page_obj.previous_page_number.querystring }}">
<span aria-hidden="true">«</span>
</a>
</li>
{% else %} {
<li class="previous disabled">
<span aria-hidden="true">«</span>
</li>
{% endif %}
{% for page in page_obj.pages %}{
{% if page %}
{
{% ifequal page page_obj.number %}
<li class="active"><a href="javascript:;">{{ page }}</a></li>
{% else %}
<li><a href="?{{ page.querystring }}" class="page">{{ page }}</a></li>
{% endifequal %}
{% else %}
<li class="disabled">
<span>...</span>
</li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}{
<li class="next">
{
<a href="?{{ page_obj.next_page_number.querystring }}">
<span aria-hidden="true">»</span>
</a>
</li>
{% else %}
<li class="next disabled">
<span aria-hidden="true">»</span>
</li>
{% endif %}
</ul>
</nav>
{% for obj in page_obj.object_list %}
{% endfor %}
六. 最终效果
七. page的常用属性
page.has_previous
page.has_next
page.previous_page_number.querystring
page.next_page_number.querystring
page.number
page.querystring
{% ifequal a b %}
{% endifequal %}