实现方式:
在views.py中需要引入
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
引入这个后创建一个方法
def index(request):
chanp= models.Atricale.objects.all().order_by("-id") #按ID降序排获取数据库中的文章的数据,去掉-是升序
paginator = Paginator(
chanp, 4) #一页显示3篇文章
page = request.GET.get('page')
try:
chanp= paginator.page(page)
except PageNotAnInteger:
chanp= paginator.page(1)
except EmptyPage:
chanp= paginator.page(paginator.num_pages)
return render(request,
index.html', {"
chanp":
chanp})
html端代码如下:
<li>
{% if
chanp.has_previous %}
<a href="?page={{
chanp.previous_page_number }}" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
{% endif %}
</li>
{% for pg
in
chanp.paginator.page_range %}
{% if
chanp.number == pg %}
<li class="active"><a href="?page={{ pg }}">{{ pg }}</a> </li>
{% else %}
<li><a href="?page={{ pg }}">{{ pg }}</a> </li>
{% endif %}
{% endfor %}
<li>
{% if
chanp.has_next %}
<a href="?page={{
chanp.next_page_number }}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
{% endif %}</li>
效果图:
![](https://i-blog.csdnimg.cn/blog_migrate/4efa23e103b607a0c7aad38ecccb86fa.png)