Django Blog Pagination

  • views.py
    from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
    from django.shortcuts import render
    
    
    def index(request):
        latest_posts_list = Post.objects.filter(is_public=True).order_by('-created')
        page = request.GET.get('page', 1)
        paginator = Paginator(latest_posts_list, 10) # Show 10 posts per page
    
        try:
            latest_posts = paginator.page(page)
        except PageNotAnInteger:
            latest_posts = paginator.page(1)
        except EmptyPage:
            latest_posts = paginator.page(paginator.num_pages)
    
        context = {
            'latest_posts': latest_posts,
        }
    
        return render(request, 'blog/index.html', context)
  • template index.html
    {% block content %}
    
    <ul>
        {% for post in latest_posts %}
        <article itemscope="" itemtype="http://schema.org/Blog">
            <h2 class="entry-title" itemprop="headline"><a href="/post/{{ post.slug }}">{{ post.title }}</a></h2>
            <span class="entry-meta"><time itemprop="datePublished" datetime="{{ post.created }}">{{ post.created|date:'d M Y' }}</time></span>
        </article>
        {% endfor %}
    </ul>
    
    {% if latest_posts.has_other_pages %}
      <ul class="pagination">
        {% if latest_posts.has_previous %}
          <a href="?page=1">&laquo;</a>
          <li><a href="?page={{ latest_posts.previous_page_number }}">&lsaquo;</a></li>
        {% else %}
          <li class="disabled"><span>&laquo;</span></li>
          <li class="disabled"><span>&lsaquo;</span></li>
        {% endif %}
        {% for i in latest_posts.paginator.page_range %}
          {% if latest_posts.number == i %}
            <li class="active"><span>{{ i }}</span></li>
          {% else %}
            <li><a href="?page={{ i }}">{{ i }}</a></li>
          {% endif %}
        {% endfor %}
        {% if latest_posts.has_next %}
          <li><a href="?page={{ latest_posts.next_page_number }}">&rsaquo;</a></li>
          <a href="?page={{ latest_posts.paginator.num_pages }}">&raquo;</a>
        {% else %}
          <li class="disabled"><span>&rsaquo;</span></li>
          <li class="disabled"><span>&raquo;</span></li>
        {% endif %}
      </ul>
    {% endif %}
    
    {% endblock %}
     
  • custom.css
    .pagination {
        clear:both;
        position:relative;
        font-size:15px;
        text-align:center;
    }
    
    .pagination span, .pagination a {
        display:inline-block;
        margin: 2px 2px 2px 0;
        padding:6px 9px 5px 9px;
        text-decoration:none;
    }
    
    .pagination .current{
        padding:6px 9px 5px 9px;
        font-weight: bold;
    }
    .pagination li{
      display: inline;
      list-style: none;
    }
     


Resources:

➡️https://docs.djangoproject.com/en/2.2/topics/pagination/

➡️https://simpleisbetterthancomplex.com/tutorial/2016/08/03/how-to-paginate-with-django.html