码迷,mamicode.com
首页 > 其他好文 > 详细

django分页

时间:2017-04-12 15:12:41      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:个数   reg   top   article   tags   tag   cat   integer   menu   

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 ‘‘

 

django分页

标签:个数   reg   top   article   tags   tag   cat   integer   menu   

原文地址:http://www.cnblogs.com/hongpeng0209/p/6699067.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!