Django 分页的简单实现

Django分页比较简单,它内置了一个Paginator类.这样对分页的操作只需要明白这个类就OK了。
def list(request):
    after_range_num = 5
    bevor_range_num = 4
    try:
        page = int(request.GET.get("page",1))
        print('page----->',page)
        if page < 1:
            page = 1
    except ValueError:
        page = 1
    
    info = Article.objects.order_by('id').all()
    paginator = Paginator(info,3)
    
    
    try:
        articleList = paginator.page(page)
    except(EmptyPage,InvalidPage,PageNotAnInteger):
        articleList = paginator.page(1)
    print('articleList---->',articleList.object_list)
    #显示范围
    if page >= after_range_num:
        page_range = paginator.page_range[page-after_range_num:page+bevor_range_num]
    else:
        page_range = paginator.page_range[0:int(page)+bevor_range_num]
    return render_to_response("blogsite/list.html",locals())

以上是分页的controller.html代码如下:
{% if info %}
	{% for article in articleList.object_list %}
		<div class="article">
			<div class="title">-----<a href='/blogsite/{{ article.id }}'>{{ article.title }}</a></div>
		</div>
	{% endfor %}
{% else %}
	<p>对不起没有文章奥!</p>
{% endif %}

<hr>
{% if has_previous %}
	<a href="/?page={{ previous }}">上一页</a>
{% endif %}
{% if has_next %}
	<a href="/?page={{ next }}"></a>
{% endif %}
<hr>
{% if articleList.has_previous %}
<a href="?page={{ articleList.previous_page_number }}" title="下一页">上一页</a>&nbsp;
{% endif %}
{% for p in page_range %}
{% ifequal p articleList.number %}
<span>{{p}}</span>
{% else %}
<a href="?page={{p}}" title="第{{p}}页">{{p}}</a>
{% endifequal %}
{% endfor %}
&nbsp;
{% if articleList.has_next %}
<a href="?page={{ articleList.next_page_number }}" title="下一页">下一页</a>&nbsp;
{% endif %}

你可能感兴趣的:(html,django,python)