Django-pure-pagination的使用
Django自带了两个分页类,但相较于第三方分页模块django-pure-pagination,它们使用起来可能不够方便。以下介绍如何使用django-pure-pagination,该库基于django.core.pagination进行改进。
- 安装模块:
pip install django-pure-pagination
- 配置: 在settings.py中添加 ‘pure_pagination’ 到 INSTALLED_APPS。
INSTALLED_APPS = ( ... 'pure_pagination', )
也可以在settings.py中加入一些分页配置,例如以下配置将以10页为节点进行隐藏:pythonCopy codePAGINATION_SETTINGS = { 'PAGE_RANGE_DISPLAYED': 10, 'MARGIN_PAGES_DISPLAYED': 2, 'SHOW_FIRST_PAGE_WHEN_INVALID': True, }
- 在views中使用:
from pure_pagination import Paginator, PageNotAnInteger def category(request, pk): category = get_object_or_404(Category, pk=pk) article_list = Article.objects.filter(category=pk).order_by('-update_time') try: page = request.GET.get('page', 1) except PageNotAnInteger: page = 1 paginator = Paginator(article_list, 5, request=request) articles = paginator.page(page) return render(request, 'bbs/list.html', {'articles': articles})
其中Paginator(article_list, 5, request=request)
中的5表示每页展示的数据量。 - 在模板中使用:
{% for article in articles.object_list %} <!-- ... --> {% endfor %} <div id="pgt" class="bm bw0 pgs cl"> <span id="fd_page_top"> <div class="pg"> {% for page in articles.pages %} {% if page %} {% ifequal page articles.number %} <strong>{{ page }}</strong> {% else %} <a href="?{{ page.querystring }}">{{ page }}</a> {% endifequal %} {% else %} <a>....</a> {% endif %} {% endfor %} {% if articles.has_next %} <a href="?{{ articles.next_page_number.querystring }}" class="nxt">Next</a> {% endif %} </div> </span> {% if articles.has_previous %} <span class="pgb y" initialized="true"><a href="?{{ articles.previous_page_number.querystring }}">Previous</a></span> {% endif %} </div>
- 其他方法:
<div class="pageturn"> <ul class="pagelist"> {% if articles.has_previous %} <li class="long"><a href="?{{ articles.previous_page_number.querystring }}">Previous</a></li> {% endif %} {% for page in articles.pages %} {% if page %} {% ifequal page articles.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 articles.has_next %} <li class="long"><a href="?{{ articles.next_page_number.querystring }}">Next</a></li> {% endif %} </ul> </div>
- 其他用法:
{% ifequal page1 page2 %} {% endifequal %}
使用django-pure-pagination,你可以轻松配置并在Django项目中实现更便捷的分页功能。
© 版权声明
THE END
暂无评论内容