Python - DjangoPython语言与信息数据获取和机器学习

Django - Pagination分页

2017-08-17  本文已影响63人  廖马儿

分页示例:

在views.py中:

from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger


def ProductList(request):

    data = getData()

    winery = models.Winery.objects.all().order_by("-id") # 以id倒序

    paginator = Paginator(winery, 3) # 3个为一页
    page = request.GET.get('page')

    try:
        wine = paginator.page(page)
    except PageNotAnInteger:  # page不是integer
        wine = paginator.page(1)
    except EmptyPage:   # 如果传递的page不在我们的分页范围中
        wine = paginator.page(paginator.num_pages)

    data["winery"] = wine 

    return render(request, 'productlist.html',  {'data':data})

# 在模板中

 <div class="pagination ">
        <span class="step-links">
            {% if data.winery.has_previous %}
            <a href="?page={{ data.winery.previous_page_number }}">上一页</a>
            {% endif %}
             
            <span class="current ">
                第{{ data.winery.number }}页,共{{ data.winery.paginator.num_pages }}页
            </span>
            {% if data.winery.has_next %}
             
            <a  href="?page={{ data.winery.next_page_number }}">下一页</a>
            {% endif %}
        </span>
    </div>

注意:我们一般是在settings.py中设置分页大小:

# 自定义
PRODUCT_PAGE_SIZE = 3

views.py中:

paginator = Paginator(winery, settings.PRODUCT_PAGE_SIZE) # 3个为一页
上一篇下一篇

猜你喜欢

热点阅读