使用默认的分页器
数据库内存的数据较多,读取的时候一页太长,因此需要使用分页器进行分页,在 Django 的 views 内声明。
views.py1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.shortcuts import render
from django.views.decorators.clickjacking import xframe_options_exempt
from NetEase.models import NetEase
@xframe_options_exempt def news(request): limit = 4 article = NetEase.objects paginator = Paginator(article, limit) page_num = request.GET.get('page', 1) page_num = int(page_num) try: loaded = paginator.page(page_num) except ValueError: loaded = paginator.page(1) except PageNotAnInteger: loaded = paginator.page(1) except EmptyPage: loaded = paginator.page(paginator.num_pages) context = { 'NetEase': loaded } return render(request, 'NetEase/news.html', context)
|
这样,在 URL 上就可以通过 ?page=x
来访问第 x 页的数据,例如:http://127.0.0.1:8000/news.html?page=6
展示的就是第六页的数据。
上下页及跳转
为了方便,在前端上做一个上下页以及跳转的按钮。
news.html1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| <div> <ul class="fy"> {% if NetEase.has_previous %} <li><a href="?page={{ NetEase.previous_page_number }}"> 上一页</a></li> {% endif %} <li>{{ NetEase.number }} of {{ NetEase.paginator.num_pages }}</li> {% if NetEase.has_next %} <li><a href="?page={{ NetEase.next_page_number }}">下一页</a></li> {% endif %} <div class="tiaozhao"> {# <form action="?page={{ page }}" method="post">#} <label> <input type="text" class="wb" id="page"/> </label> <input type="submit" class="tj" value="跳转" onclick="tz()"/> {# </form>#} </div>
<div class="clear"></div> </ul> </div> <script type="text/javascript" src="{% static 'js/nav.js' %}"></script> <script type="text/javascript"> function tz() { {#alert("?page=" + document.getElementById("page").value);#} window.location.href = "?page=" + document.getElementById("page").value; } </script>
|
最终效果:
异常输入也没问题,会跳转到第一页,代码在 views 内。