Pagination
views.py
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def allblog(request):
post_list = Post.objects.all()
most_recent = Post.objects.order_by('-timestamp')[:5]
paginator = Paginator(post_list, 6)
#page = request.GET.get('page')
page_request_var = 'page'
page = request.GET.get(page_request_var)
try:
allPosts = paginator.page(page)
except PageNotAnInteger:
allPosts = paginator.page(1)
except EmptyPage:
allPosts = paginator.page(paginator.num_pages)
context={
'allPosts': allPosts,
'most_recent': most_recent,
'page_request_var': page_request_var,
}
return render(request, "website/allblog.html", context)
html
<!-- Pagination -->
<nav aria-label="Page navigation example">
<ul class="pagination pagination-template d-flex justify-content-center">
{% if allPosts.has_previous %}
<li class="page-item"><a href="?{{ page_request_var }}={{ allPosts.previous_page_number }}" class="page-link"> <i class="fa fa-angle-left"></i></a></li>
{% endif %}
<li class="page-item"><a href="?{{ page_request_var }}={{ allPosts.number }}" class="page-link active">{{ allPosts.number }}</a></li>
{% if allPosts.has_next %}
<li class="page-item"><a href="?{{ page_request_var }}={{ allPosts.next_page_number }}" class="page-link"> <i class="fa fa-angle-right"></i></a></li>
{% endif %}
</ul>
</nav>