django自带分页(补)
2017-07-18 本文已影响0人
赖三石
注:只突出分页,其余功能可能不全
例:
views.py
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def index(request):
article_list = models.Article.objects.all().order_by('-publish_date')
paginator = Paginator(article_list, 3) # Show 25 contacts per page
page = request.GET.get('page')
try:
articles = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
articles = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
articles = paginator.page(paginator.num_pages)
return render(request,'index.html',{
'articles': articles
})
template
{% for article in articles %}
<div class="blog-box row">
<div class="head-img col-md-4">
![](/static/{{ article.head_img }})
</div>
<div class="blog-summary-box col-md-8">
<h3> <a href="{% url 'article' article.id %}">{{ article.title }}</a></h3>
<div class="blog-summary-btn">
<a>{{ article.author.name }}</a>
<span>{{ article.publish_date }}></span>
<span><i class="fa fa-star"></i>4</span>
<span><i class="fa fa-comment-o"></i>9</span>
<span><i class="fa fa-wechat"></i></span>
</div>
<div class="blog-summary">
{{ article.summary }}
</div>
</div>
</div>
{% endfor %}
<nav>
<ul class="pagination">
{% if articles.has_previous %}
<li ><a href="?page={{ articles.previous_page_number }}" >上一页</a></li>
{% endif %}
{% for p_num in articles.paginator.page_range %}
{% if p_num == articles.number %}
<li class="active"><a href="?page={{ p_num }}">{{ p_num }}</a></li>
{% else %}
<li ><a href="?page={{ p_num }}">{{ p_num }}</a></li>
{% endif %}
{% endfor %}
{% if articles.has_next %}
<li ><a href="?page={{ articles.next_page_number }}" >下一页</a></li>
{% endif %}
</ul>
</nav>