django自带分页
1 from django.core.paginator import Paginator
2 l = range(1,51)
3 page_obj = Paginator(l,20)
4 print(list(page_obj.page(2)))#获取第2页数据
5 print(page_obj.count)#总共多少条数据
6 print(page_obj.num_pages)#总共分了多少页
7
8 print(page_obj.page_range)#分页范围
9 cur_page = page_obj.page(2)
10 print(cur_page.has_previous())#判断是否有上一页
11 print(cur_page.previous_page_number())#返回上一页的页码,没有上一页会报错
12 print(cur_page.has_next())#判断是否有下一页
13 print(cur_page.next_page_number())#返回下一页的页码,没有下一页会报错
14 print(cur_page.has_other_pages())#判断是否有其他页,对只有一页数据判断
15 print(cur_page.paginator)#获取当前页的分页对象也就是page_obj
view.py 视图中使用分页
1 from django.core.paginator import Paginator
2 from .const import page_size
3 # Create your views here.
4 def index(request):#首页
5 #数据来源数据库时,要引用到这个表的这个类
6 # catagories = Category.objects.filter(is_delete=False)#获取所有数据
7 page = request.GET.get('page',1)#从url获取page值,获取不到时取1
8 limit = request.GET.get('limit',page_size)
9 article = Article.objects.filter(is_delete=False)
10 page_obj = Paginator(article,limit)
11 page_data = page_obj.page(page)
12 data = {'articles':page_data}
13 return render(request,'index.html',data)#引用数据需要通过字典data引用
模板html中使用分页样式
1 {% if articles.has_other_pages %}
2 <div class="pagelist">
3 {% if articles.has_previous %}
4 <a class="allpage" href="/index?page={{ articles.previous_page_number }}"><b>上一页</b></a>
5 {% endif %}
6 {% for page_num in articles.paginator.page_range %}
7 <a href="/index?page={{ page_num }}&limit=10" class="curPage">{{page_num}}</a>
8 {% endfor %}
9 {% if articles.has_next %}
10 <a href="#" onclick="page(2)">下一页</a>
11 {% endif %}
12 </div>
13 {% endif %}