Menu Close

How to use pagination with Python Django class based generic ListViews?

To use pagination with Python Django class based generic ListViews, w we can create our own view class that inherits from the ListView class.

For instance, we write

import models
from django.views.generic import ListView

class CarListView(ListView):
    model = models.Car      
    template_name = 'app/car_list.html' 
    context_object_name = "car_list"
    paginate_by = 10

to create the CarListView that returns the Car model values in paginated form in views.py.

We render the app/car_list.html template by writing

template_name = 'app/car_list.html' 

And we set paginate_by to 10 to return 10 items per page.

Then in car_list.html, we write

{% if car_list %}
    <table id="cars">
        {% for car in car_list %}
            <tr>
                <td>{{ car.model }}</td>
                <td>{{ car.year }}</td>
                <td><a href="/car/{{ car.id }}/" class="see_detail">detail</a></td>
            </tr>
        {% endfor %}
    </table>
    {% if is_paginated %}
        <div class="pagination">
            <span class="page-links">
                {% if page_obj.has_previous %}
                    <a href="/cars?page={{ page_obj.previous_page_number }}">previous</a>
                {% endif %}
                <span class="page-current">
                    Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
                </span>
                {% if page_obj.has_next %}
                    <a href="/cars?page={{ page_obj.next_page_number }}">next</a>
                {% endif %}
            </span>
        </div>
    {% endif %}
{% else %}
    <h3>My Cars</h3>
    <p>No cars found!!! :(</p>
{% endif %}

to render car_list items with a for loop.

And we if is_paginated is True.

If it is, then we render links to the previous and next page with previous_page_number and next_page_number .

Posted in Python, Python Answers