Blog Update: Added Pagination to Index

by Aaron Crowder on

I realized after I'd written more than five posts that I forgot to add pagination to the index of this blog. I finally found a few spare minutes this evening to add it. I figured with Django that it would be fairly easy, but as always with Django I was impressed with just HOW easy it was.

First, I had to add a single paginate_by property to my ListView for the index:

class IndexView(ListView):
    paginate_by = 5

Then in my view I was able to use the page_obj to iterate over my posts and show some links to navigate pages:

{% for post in page_obj %}
...
{% endfor %}

<div>
    {% if page_obj.has_previous %}
        <a href="?page={{ page_obj.previous_page_number }}">Previous Page</a>
    {% endif %}
    Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
    {% if page_obj.has_next %}
        <a href="?page={{ page_obj.next_page_number }}">Next Page</a>
    {% endif %}
</div>

#updates #code