django提供的分页器实现分页
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def category(request,category_id): # raise ValueError categories = models.Category.objects.filter(set_as_top_menu=True) if category_id == "all": articles = models.Article.objects.all().order_by("-id") else: articles = models.Article.objects.filter(category_id=category_id).order_by("-id") paginator = Paginator(articles, 2) # 每页显示的个数 page = request.GET.get('page')#总页数 try: objs = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. objs = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. objs = paginator.page(paginator.num_pages) return render(request,'index.html', {"categories":categories, "articles":objs})
html
{% load bbs_tags %}
<nav aria-label="..."> <ul class="pagination"> {% for page in articles.paginator.page_range %} {% if articles.number == page %} <li class="active"><a href="?page={{ page }}">{{ page }} <span class="sr-only">(current)</span></a></li> {% else %} {% render_paginator_btn articles page %} {% endif %} {% endfor %} </ul> </nav>
bbs_tags
@register.simple_tag def render_paginator_btn(articles,page): current_page = articles.number total_page = articles.paginator.num_pages display_count = 7#总页数 if current_page - 0 < 4 and page <= display_count: return mark_safe('<li><a href="?page={page}">{page}</a></li>'.format(page=page)) elif total_page - current_page < 3 and page > total_page - display_count: return mark_safe('<li><a href="?page={page}">{page}</a></li>'.format(page=page)) elif abs(page - current_page) < 4: return mark_safe('<li><a href="?page={page}">{page}</a></li>'.format(page=page)) return ''