自定義分頁樣式
阿新 • • 發佈:2022-12-09
一.基本安裝和配置
1.pip install django-pure-pagination 2. settings.py中 install app中新增'pure_pagination', 3. settings.py中新增引數 PAGINATION_SETTINGS = { 'PAGE_RANGE_DISPLAYED': 2, 'MARGIN_PAGES_DISPLAYED': 2, 'SHOW_FIRST_PAGE_WHEN_INVALID': True, } PAGE_RANGE_DISPLAYED:總共會顯示多少頁。下面例子中從1到100的話,這裡要設為100 MARGIN_PAGES_DISPLAYED:旁邊會顯示多少個。 SHOW_FIRST_PAGE_WHEN_INVALID:當輸入頁數不合法是否要跳到第一頁
二. view中新增分頁配置
def author_list(request): all_authors = Author.objects.all() try: page = request.GET.get('page', 1) except PageNotAnInteger: page = 1 p = Paginator(all_authors,2,request=request) #2 表示每頁的數量 page_1 = p.page(page) return render(request, 'web/fenye.html', locals())
三. 前端展示程式碼
1.資料展示部分程式碼中的物件修改,這裡page_1要改成page_1.object_list
<div id="content"> <div style="padding-left: 25px; "> <table class="table" > <thead> <tr> <th>文章名稱</th> </tr> </thead> <tbody> {% for row in page_1.object_list %} <tr> <td>{{ row.username }}</td> </tr> {% endfor %} </tbody> </table> </div> </div>
2.分頁需結合bootstrap
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
3.自定義分頁部分程式碼如下
預設樣式可以使用{{page_1.render}},即可完成分頁
<nav aria-label="Page navigation">
<ul class="pagination">
{% if page_1.has_previous %}
<li>
<a href="?{{ page_1.previous_page_number.querystring }}" aria-label="Previous">
<span aria-hidden="true">上一頁</span>
</a>
</li>
{% else %}
<li class="disabled">
<a aria-label="Previous">
<span aria-hidden="true">上一頁</span>
</a>
</li>
{% endif %}
{% for page in page_1.pages %}
{% if page %}
{% ifequal page page_1.number %}
<li class="active"><a href="?{{ page.querystring }}">{{ page }}</a></li>
{% else %}
<li><a href="?{{ page.querystring }}">{{ page }}</a></li>
{% endifequal %}
{% else %}
...
{% endif %}
{% endfor %}
{% if page_1.has_next %}
<li>
<a href="?{{ page_1.next_page_number.querystring }}" aria-label="Next">
<span aria-hidden="true">下一頁</span>
</a>
</li>
{% else %}
<li class="disabled">
<a aria-label="Next">
<span aria-hidden="true">下一頁</span>
</a>
</li>
{% endif %}
</ul>
其中page_1要就是view中自己定義的分頁物件。
參考:
https://blog.csdn.net/L1119873113/article/details/95374720
https://blog.csdn.net/weixin_42289273/article/details/108887160