我对django paginator做错了什么

时间:2016-04-12 13:19:48

标签: python django pagination paginator

我试图按照official documentation使用django paginator。但它只显示" Page of。" 我做错了什么?

有我的views.py:

from django.shortcuts import render, get_object_or_404, render_to_response
from django.utils import timezone
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import Post

def post_list(request):
    posts = Post.objects.order_by('-created_date')
    return render(request, 'blog/post_list.html', {'posts': posts})

def post_detail(request, pk):
        post = get_object_or_404(Post, pk=pk)
        return render(request, 'blog/post_detail.html', {'post': post})

def listing(request):
    article_list = Post.objects.all()
    paginator = Paginator(article_list, 25) # 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, 'blog/post_list.html', {'articles': articles})

我的post_list.html:

<div class="pagination">
    <span class="step-links">
        {% if articles.has_previous %}
            <a href="?page={{ articles.previous_page_number }}">previous</a>
        {% endif %}

        <span class="current">
            Page {{ articles.number }} of {{ articles.paginator.num_pages }}.
        </span>

        {% if articles.has_next %}
            <a href="?page={{ articles.next_page_number }}">next</a>
        {% endif %}
    </span>
</div>

1 个答案:

答案 0 :(得分:2)

您正在呈现post_list视图,而不是listing视图。您有两种选择:

  1. 更改您的网址,以便根网址指向listing视图:

    urlpatterns = [ 
        url(r'^$', views.listing, name='listing'), 
        url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'), 
    ]
    
  2. listing视图创建新网址。

    urlpatterns = [ 
        url(r'^$', views.post_list, name='post_list'), 
        url(r'^listing/$', views.listing, name='listing'),
        url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'), 
    ]
    
  3. 同样,你应该只做其中一件事,而不是两者。