python - Django简单实现分页展示功能(附源码)

后台处理数据传递给前台模板:

python - Django简单实现分页展示功能(附源码)_第1张图片

然后模板渲染展示:

python - Django简单实现分页展示功能(附源码)_第2张图片

 

下边是源码:

 

接口:

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
    
def f(request):
    stu = models.Stu.objects.all()
    
    page = Paginator(stu, 2)
    page_id = request.GET.get('page_id')
    if page_id:
        try:
            stus = page.page(page_id)
        except PageNotAnInteger:
            stus = page.page(1)
        except EmptyPage:
            stus = page.page(1)
    else:
        stus = page.page(1)
    return render(request,'f.html',locals())

模板:

{% for i in stus %}
{{i.name}}<br>
{% endfor %}


<div>
{% if stus.has_previous %}
    <a href="/f?page_id={{stus.previous_page_number}}">
        <button><<>
    a>
{% endif %}


{% for i in page.page_range %}
    <a href="/f?page_id={{i}}">
        <button>{{i}}button>
    a>
{% endfor %}


{% if stus.has_next %}
    <a href="/f?page_id={{stus.next_page_number}}">
        <button>  >>  button>
    a>
{% endif %}

然后就非常简单的实现了分页功能了!

转载于:https://www.cnblogs.com/kitshenqing/p/11063173.html

你可能感兴趣的:(python - Django简单实现分页展示功能(附源码))