Django 内置分页的简单使用

1, 文档
https://docs.djangoproject.com/en/1.11.1/topics/pagination/ 
2,视图

  from django.core.paginator import Paginator,EmptyPage, PageNotAnInteger
   picture_list = Picture.objects.all().only("avatar").order_by("pk") # 注:查询数据一定要排序,否则会有错误警告(但不会影响使用)!
# 使用django 自带分页 # contact_list = Contacts.objects.all() paginator = Paginator(picture_list, 12) # 每一页的数据个数 page = request.GET.get('page') try: picture_data = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. picture_data = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. picture_data = paginator.page(paginator.num_pages) return render(request,"picture.html",{"picture_data":picture_data})
3,html
{% for picture in picture_data %}
    {# Each "contact" is a Contact model object. #}
            <a href="{{ picture.avatar }}"><img src="{{ picture.avatar }}" alt="error" title="原图" height="420px" width="310px"></a>
{% endfor %}

<div class="pagination">
    <span class="step-links">
        {% if picture_data.has_previous %}
            <a href="?page=1">首页</a>
            <a href="?page={{ picture_data.previous_page_number }}">上一页</a>
        {% endif %}

        {% if picture_data.has_next %}
            <a href="?page={{ picture_data.next_page_number }}">下一页</a>
            <a href="?page={{ picture_data.paginator.num_pages }}">尾页</a>
        {% endif %}

        <span class="current">
            第{{ picture_data.number }}页 ,一共 {{ picture_data.paginator.num_pages }} 页.
        </span>
    </span>
</div>

 

 


posted @ 2019-03-12 15:52  一种清孤不等闲  阅读(470)  评论(0编辑  收藏  举报
Live2D