Reputation: 367
So, I am trying to add pagination to my django website. Here is the code for my view function that handles pagination:
def index(request):
object_list = Post.published.all()
latest_post = object_list.last()
paginator = Paginator(object_list, 3)
page = request.GET.get('page')
try:
posts = Paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
return render(request, 'blog/index.html',{
'posts':posts,
'latest_post':latest_post,
'page':page,
})
I am getting an error on line 11, inside the try
block. Where is the error?
Upvotes: 0
Views: 1235
Reputation: 3364
request.GET.get('page')
returns None
and thus it fails in the next line because page number is required. It's better to use Pagination this way:
paginator = Paginator(object_list, 3)
page = request.GET.get('page')
posts = paginator.get_page(page)
get_page()
method handles this case and it will return page 1 in case it's None
. Here is the line in the source code where this happens.
Upvotes: 1