django中的分页设置
1、在控制台中的展示
from django.core.paginator import Paginator iter = 'abcdefghijklmn' inator = Paginator(iter, 5) page1 = inator.page(1) page1.object_list # 输出当前也的内容 'abcde' page1.number # 输出页码 1 page1.has_next() # 输出是否有下一页 True page1.next_page_number() # 输出下一页的页码 2 print(page1.paginator.num_pages) # 输出总的页数 3
2、用在web中会有很大的不同
1> html中的设置
使用ArtiInfo(参见views.py)而不是上面的page1,此外方法也没有括号
{% for item in ArtiInfo %}
<li>
<img src="{% static 'images/0001.jpg' %}" width="100" height="91">
<div class="article-info">
<h3><a href="#">{{ item.title }}</a></h3>
<p class="meta-info">
{% for tag in item.tags %}
<span class="meta-cate">{{ tag }}</span>
{% endfor %}
</p>
<p class="description">{{ item.des }}</p>
</div>
<div class="rate">
<span class="rate-score">{{ item.scores }}</span>
</div>
</li>
{% endfor %}
<div class="main-content-pagitor">
{% if ArtiInfo.has_previous %}
<a href="?page={{ ArtiInfo.previous_page_number }}">< Pre</a>
{% endif %}
<span> {{ ArtiInfo.number }} of {{ ArtiInfo.paginator.num_pages }} </span>
{% if ArtiInfo.has_next %}
<a href="?page={{ ArtiInfo.next_page_number }}">Next ></a>
{% endif %}
</div>
2> models.py
from django.db import models from mongoengine import * class ArtiInfo(Document): des = StringField() title = StringField() scores = StringField() tags = ListField(StringField()) # 对应数据库中已存在的数据表 meta = {'collection':'articles'}
3> views.py
,views.py from django.shortcuts import render from django_web.models import ArtiInfo from django.core.paginator import Paginator def index(request): limit = 5 arti_info = ArtiInfo.objects[:20] paginatior = Paginator(arti_info,limit)
# 参考上面html中是怎么设置的 page = request.GET.get('page',1) print(request) print(request.GET) loaded = paginatior.page(page) context = { 'ArtiInfo':loaded } return render(request,'index.html',context)
注意,上面html中使用的ArtiInfo不是models.py中定义的类,而是在views.py中的context字典中的键ArtiInfo