用到以下对象的属性和方法:
- Paginator对象
- Page对象
- template层
<ul>书籍列表
{% for book in booklist %}
<li><a href="{% url 'booktest:getBookDetails' book.pk %}">{{ book }}</a><a href="{% url 'booktest:updateBook' bid=book.pk %}"> 编辑 </a><a href="{% url 'booktest:deleteBookHandle' bid=book.pk %}"> 删除</a></li>
{% endfor %}
<a href="{% url 'booktest:home' %}?pIndex=1">first</a>
{% if booklist.has_previous %}
<a href="{% url 'booktest:home' %}?pIndex={{ booklist.previous_page_number }}">上一页</a>
{% endif %}
{% for pageIndex in page_range %}
{% if booklist.number == pageIndex %}
{{ pageIndex }}
{% else %}
<a href="{% url 'booktest:home'%}?pIndex={{ pageIndex }}">{{ pageIndex }}</a>
{% endif %}
{% endfor %}
{% if booklist.has_next %}
<a href="{% url 'booktest:home' %}?pIndex={{ booklist.next_page_number }}">下一页</a>
{% endif %}
<a href="{% url 'booktest:home' %}?pIndex={{ booklist.paginator.num_pages }}">尾页</a>
</ul>
- views层
def home(request):
#首页取session的uname,如果有值展示uname,如果没有展示为空
uname = request.session.get('uname','')
booklist = BookInfo.objects.all()
bpaginator = Paginator(booklist,2)
page_range = bpaginator.page_range
pIndex = request.GET.get('pIndex')
if pIndex == None:
bpage = bpaginator.page(1)
else:
bpage = bpaginator.page(pIndex)
context ={'uname':uname,'booklist':bpage,'page_range':page_range}
return render(request,'booktest/home.html',context=context)
- url配置
发生的小坑,模板中dtl对等号两边的空格敏感,会出现乱码或报错:
运行的时候上一页执行错误,url出现乱码:
对比代码发现,上一页等号两边有空格。。。。。