首页 > 代码库 > django分页
django分页
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="http://www.mamicode.com/?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="http://www.mamicode.com/?page={page}">{page}</a></li>‘.format(page=page)) elif abs(page - current_page) < 4: return mark_safe(‘<li><a href="http://www.mamicode.com/?page={page}">{page}</a></li>‘.format(page=page)) return ‘‘
django分页
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。