BLOG

Pagination in Django - Setting up pagination for Django blog in PythonAnywhere.

python

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.

  1. python
  2. Pagination in Django - Setting up pagination for Django blog in PythonAnywhere.

AUTHOR

Almost 10 years have passed since I started learning web development. Learning web development has made my life more fulfilling. This is because the greatest benefit that can be obtained in the process of learning web development is that when you encounter difficulties, you acquire the attitude of actively searching for information to solve them on your own. And just as I learned a lot from the knowledge of my predecessors, I hope that by disseminating information in English, it will reach people around the world who want to learn web development. life is very short. I would be very happy if I could add even a little bit to your life by my outputting what I learned every day. Maybe the information is incorrect or outdated at times. I'll update when I find out.