Reputation: 11
I'm trying to use django paginator by following the official documentation. But it displays only "Page of ." What am I doing wrong?
There is my 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})
And my 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>
Upvotes: 0
Views: 318
Reputation: 27092
You're rendering the post_list
view, rather than the listing
view. You have two options:
Change your URLs so that the root URL points to the listing
view:
urlpatterns = [
url(r'^$', views.listing, name='listing'),
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'),
]
Create a new URL for the listing
view.
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'),
]
Again, you should only do one of these things, not both.
Upvotes: 2