As the number of articles on your blog increases, you may want to limit the number of articles that can be displayed on the list page.
In such a case, it would be nice to add a pagination function.
This time I will introduce how to add pagination to Django blog of PythonAnywhere.
How to add pagination to Django blog in PythonAnywhere.
Add the following code to views.py.
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def paginate_queryset(request, queryset, count): paginator = Paginator(queryset, count) page = request.GET.get('page') try: page_obj = paginator.page(page) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) return page_obj
In addition, the top page will be changed as follows.
If you write 6 articles, it will be displayed on the next page from the 7th article.
def index(request): articles = Article.objects.order_by('-id') page_obj = paginate_queryset(request, articles, 6) return render(request,'blog/index.html',{'articles': page_obj.object_list,'page_obj': page_obj})
Add the following to the html file.
<ul class="pagination"> {% if page_obj.has_previous %} <li class="pagination-Item"> <a class="pagination-Item-Link" href="?page={{ page_obj.previous_page_number }}">PREV</a> </li> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <li class="pagination-Item"> <a href="?page={{ num }}" class="pagination-Item-Link isActive"><span>{{ num }}</span></a> </li> {% else %} <li class="pagination-Item"> <a href="?page={{ num }}" class="pagination-Item-Link"><span>{{ num }}</span></a> </li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li class="pagination-Item"> <a class="pagination-Item-Link" href="?page={{ page_obj.next_page_number }}">NEXT</a> </li> {% endif %} </ul>
Apply whatever CSS you like and you're done.
Please, try it.