# 14、Django分页并前端显示



### 参考：https://www.cnblogs.com/ahaii/p/5741808.html

### 自定义函数

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


def get_page(request,obj):
    paginator = Paginator(obj,20)
    page = request.GET.get('page')
    try:
        obj = paginator.page(page)
    except PageNotAnInteger:
        obj = paginator.page(1)
    except EmptyPage:
        obj = paginator.page(paginator.num_pages)
    return obj
```

### 视图

* views.py

```python
from blog.paginator import get_page

def index(request):
    post_list = Post.objects.all().order_by('-ct_time')
    post_list = get_page(request,obj=post_list)
    return render(request, 'blog/index.html', locals())
```



### 前端页面

* page.html

```html
<nav aria-label="Page navigation example">
    <ul class="pagination justify-content-end">

        <!--如果有上一页,就显示左箭头,如果没有上一页(即当前为第一页),就不会显示-->
        {% if post_list.has_previous %}
        <li class="page-item "><a class="page-link" href="?page={{ post_list.previous_page_number }}">上一页</a></li>
        {% endif %}


        <!--  中间页码显示部分  -->
        {% for page_num in post_list.paginator.page_range %}
        {% if page_num == post_list.number %}
        <li class="page-item active"><a class="page-link" href="#">{{ page_num }}</a></li>
        {% else %}
        <li class="page-item"><a class="page-link" href="?page={{ page_num }}">{{ page_num }}</a></li>
        {% endif %}
        {% endfor %}


        <!--如果有下一页,就显示右箭头,如果没有下一页(即当前为最后一页),就不会显示-->
        {% if post_list.has_next %}
        <li class="page-item"><a class="page-link" href="?page={{ post_list.next_page_number }}">Next</a></li>
        {% endif %}

    </ul>
</nav>
```

```html
{% include 'blog/page.html' %}
```

### 效果

![](https://2134947750-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvILwbD2PrkBCkSitM3m4%2Fuploads%2FrO8ykQxrOA7fB58PieTY%2Fimage-20211113153339102.png?alt=media\&token=b4940e45-627f-4262-aa79-9f1215c642d9)
