Django-分页-内置

View文件


# 分页
def index2(req):
    from django.core.paginator import Paginator, Page, PageNotAnInteger, EmptyPage

    cur_page = req.GET.get('page')
    user_list = models.UserInfo.objects.all()
    paginator = Paginator(user_list, 10)   # 分页对象
    # per_page 每页数目
    # count 数据个数
    # num_pages 总页数
    # page_range 页数范围
    # page page对象
    print(paginator.per_page, paginator.page_range,paginator.count)
    print(paginator.num_pages)
    try:
        posts = paginator.page(cur_page)
        print(posts.has_previous(), posts.previous_page_number(), posts.has_next(), posts.next_page_number())

    except PageNotAnInteger as e:
        posts = paginator.page('1')
    except EmptyPage as e:
        posts = paginator.page('1')

    return render(req, 'index2.html',{'posts':posts})

模板




    
    Title


    {% for i in posts.object_list %}
  • {{ i.user }}
  • {% endfor %}
{% if posts.has_previous %} pre {% endif %} {#中间页码#} {% for num in posts.paginator.page_range %} {{ num }} {% endfor %} {% if posts.has_next %} next {% endif %}

你可能感兴趣的:(Django)