Django之分页显示文章

1.项目:http://www.cnblogs.com/jasonhaven/p/7493422.html

2.任务描述:页面分页显示文章

3.源代码

后台:

from django.core.paginator import Paginator, InvalidPage, EmptyPage, PageNotAnInteger
from models import *
def getPage(request):
    article_list = Article.objects.all()
    paginator = Paginator(article_list, 2)
    try:
        page = int(request.GET.get('page', 1))
        article_list = paginator.page(page)
    except (EmptyPage, InvalidPage, PageNotAnInteger):
        article_list = paginator.page(1)
    return article_list

前台:

{% block left_content %}
    {% include 'ad.html' %}<!--广告-->
    <div class="topnews">
        <h2>最新文章</h2>
        {% for article in article_list %}
            <div class="blogs">
                <ul>
                    <h3><a href="{% url 'article' %}?id={{ article.id }}">{{ article.title }}</a></h3>
                    <p>{{ article.desc }}</p>
                    <p class="autor"><span class="lm f_l">
              {% for tag in article.tag.all %}<a href="/">{{ tag.name }}</a> </span>{% endfor %}<span
                            class="dtime f_l">{{ article.date_publish | date:'Y-m-d' }}</span><span class="viewnum f_r">浏览(<a
                            href="/">{{ article.click_count }}</a>)</span><span class="pingl f_r">评论(<a
                            href="/">{{ article.comment_set.all.count }}</a>)</span></p>
                </ul>
            </div>
        {% endfor %}
    </div>
    {% include 'pagination.html' %}<!--翻页-->
{% endblock %}

pageination.html

<div id="pagination">
    <ul id="pagination-flickr">
    {% if article_list.has_previous %}
    <li class="previous"><a href="?page={{ article_list.previous_page_number }}{% if request.GET.year %}&year={{ request.GET.year }}{% endif %}{% if request.GET.month %}&month={{ request.GET.month }}{% endif %}{% if request.GET.cid %}&cid={{ request.GET.cid }}{% endif %}">«上一页</a></li>
    {% else %}
    <li class="previous-off">«上一页</li>
    {% endif %}
     <li class="active">{{ article_list.number }}/{{ article_list.paginator.num_pages }}</li>
    {% if article_list.has_next %}
      <li class="next"><a href="?page={{ article_list.next_page_number }}{% if request.GET.year %}&year={{ request.GET.year }}{% endif %}{% if request.GET.month %}&month={{ request.GET.month }}{% endif %}{% if request.GET.cid %}&cid={{ request.GET.cid }}{% endif %}">下一页 »</a></li>
    {% else %}
      <li class="next-off">下一页 »</li>
    {% endif %}
   </ul>
</div>

4.运行结果

原文地址:https://www.cnblogs.com/jasonhaven/p/7520555.html