Paginated Listing with Bootstrap 5 and Django - 11

Video thumbnail

The next step is to create a paginated listing in Django as we did in previous chapters:

mystore\elements\views.py

from django.shortcuts import render
from django.core.paginator import Paginator

from .models import Element

# Create your views here.

def index(request):
   elements = Element.objects.filter(type=2).all()
   paginator = Paginator(elements,10)
   page_number = request.GET.get('page')

   return render(request,'elements/index.html', {'elements': paginator.get_page(page_number)})
La operación de:
filter(type=2)
Video thumbnail

As you can see, a paginated listing in Django consists of getting all the data and using Django's Paginator class.

It corresponds to the product type according to the data set in Django Admin and which you can configure as you like according to the value of the PK set.

For the template, we use the menu component:

mystore\elements\templates\elements\index.html

{% extends "base.html" %}

{% block content %}
   {% for e in elements %}
       <div class="card mt-2">
           <div class="card-header">
               <h4>{{e.title}}</h4>
           </div>
           <div class="card-body">
               <p>{{e.description}}</p>
           </div>
       </div>
   {% endfor %}

   {% include "partials\pagination.html" with page_obj=elements %}

{% endblock %}

The pagination.html file, which is used to build pagination links using the Bootstrap component:

elements/templates/partials/pagination.html

<nav aria-label="Page navigation example">
 <ul class="pagination justify-content-center mt-3">

       {% if page_obj.has_previous %}
           <li class="page-item">
               <a class="page-link" href="?page={{ page_obj.previous_page_number }}">prev</a>
           </li>
       {% endif %}

       {% for i in page_obj.paginator.page_range %}

           {% if i == page_obj.number %}
               <li class="page-item active">
                   <a class="page-link" href="#">{{ i }}</a>
               </li>
           {% else %}
               <li class="page-item">
                   <a class="page-link" href="?page={{ i }}">{{ i }}</a>
               </li>
           {% endif %}

       {% endfor %}

       {% if page_obj.has_next %}
           <li class="page-item">
               <a class="page-link" href="?page={{ page_obj.next_page_number }}">next</a>
           </li>
       {% endif %}
 </ul>
</nav>

I agree to receive announcements of interest about this Blog.

Let's build the listing page with B5.

- Andrés Cruz

En español

This material is part of my complete course and book; You can purchase them from the books and/or courses section, Curso y Libro desarrollo web con Django 5 y Python 3 + integración con Vue 3, Bootstrap y Alpine.js.