Search code examples
pythondjangodjango-viewsdjango-templatesdjango-pagination

How do I make my pagination show in Django template?


Goodday everyone. I want to add pagination to my home page ('index.html'). I followed the documentation of Django for pagination but I added Bootstrap's pagination to it to give a beautiful outlook.

However, it does show on my home page.

Here is the index.html code

<div class="row">
            <div class="col-md-12">
                {% if post.has_other_pages %}
                    <ul class="pagination">
                        {% if post.has_previous%}
                            <li class="page-item">
                                <a href="?page={{post.previous_page_number}}" class="page-link">&laquo;
                                </a>
                            </li>
                        {% else %}
                            <li class="page-item disabled">
                                <a class="page-link">&laquo;</a>
                            </li>
                        {% endif %}
                        {% for i in post.paginator.page_range %}
                            {% if post.number == i %}
                                <li class="page-item active">
                                    <a class="page-link">{{i}}</a>
                                </li>
                            {% else %}
                                <li class="page-item">
                                    <a href="?page={{i}}"class="page-link">{{i}}</a>
                                </li>
                            {% endif %}
                        {% endfor %}
                        {% if post.has_next%}
                            <li class="page-item">
                                <a href="?page={{post.next_page_number}}" class="page-link">&raquo;
                                </a>
                            </li>
                        {% else %}
                            <li class="page-item disabled">
                                <a class="page-link">&raquo;</a>
                            </li>
                        {% endif %}
                    </ul>
                {% endif %}
            </div>

    </div>

This is the protion that contains the pagination. Here is my views.index

def index(request):
    post = Post.objects.all()
    paginator = Paginator(post, 3)
    page = request.GET.get('page')
    page_post = paginator.get_page(page)

    context = {
        'post': page_post
    }
    return render(request, 'blog/index.html', context)

What am I doing wrong please?


Solution

  • I fixed this by posting about 6 articles from the backend instead of the three (I had initially) since I want to show just 3 articles per page. On saving this and running my server again, the pagination worked.