Django Tutorial

Django Create A Complete Project

Django Template

Django Database Query

Django Form

Django Authentication and Permission Management

Django unittest

Django Advanced

Django Paging Function

Django provides a built-in pagination feature that simplifies the process of dividing content into pages. In this tutorial, we will learn how to use Django's pagination feature to create a paging function for a list of items.

  1. Installing Django
  2. Creating a Django project and app
  3. Creating a model
  4. Adding pagination to a view
  5. Updating the template to display pagination

1. Installing Django

First, ensure that Django is installed on your system. If it's not, you can install it with the following command:

pip install django

2. Creating a Django project and app

Create a Django project and an app within the project. For this tutorial, we'll create a project called myproject and an app called myapp.

django-admin startproject myproject
cd myproject
python manage.py startapp myapp

3. Creating a model

We will create a simple Book model for this example. Add the following code to your models.py file in the myapp folder:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)

    def __str__(self):
        return self.title

Run the following commands to apply migrations and create the database table for the Book model:

python manage.py makemigrations
python manage.py migrate

4. Adding pagination to a view

Next, let's add pagination to a view. In your views.py file in the myapp folder, add the following code:

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

def book_list(request):
    books = Book.objects.all()

    # Adding pagination
    paginator = Paginator(books, 10)  # Show 10 books per page
    page = request.GET.get('page')
    books_on_page = paginator.get_page(page)

    return render(request, 'book_list.html', {'books': books_on_page})

Here, we create a Paginator object, passing in the queryset of books and the number of items to display per page. Then, we get the current page number from the request's GET parameters and use the paginator's get_page() method to get the Page object with the books for the current page. Finally, we pass the Page object to the template context.

5. Updating the template to display pagination

Create a template file called book_list.html in your myapp/templates folder and add the following code:

{% for book in books %}
  <p>{{ book.title }} by {{ book.author }}</p>
{% endfor %}

<div class="pagination">
  <span class="step-links">
    {% if books.has_previous %}
      <a href="?page=1">&laquo; first</a>
      <a href="?page={{ books.previous_page_number }}">previous</a>
    {% endif %}

    <span class="current">
      Page {{ books.number }} of {{ books.paginator.num_pages }}.
    </span>

    {% if books.has_next %}
      <a href="?page={{ books.next_page_number }}">next</a>
      <a href="?page={{ books.paginator.num_pages }}">last &raquo;</a>
    {% endif %}
  </span>
</div>

In this template, we loop through the books on the current page and display their titles and authors. We also create a pagination navigation section using the methods and properties available on the Page object.

  1. Django Pagination Example:

    • Description: Django provides built-in support for pagination using the Paginator class.
    • Code:
      from django.core.paginator import Paginator
      from django.shortcuts import render
      
      def paginated_view(request):
          queryset = MyModel.objects.all()
          paginator = Paginator(queryset, 10)  # Show 10 items per page
      
          page = request.GET.get('page')
          items = paginator.get_page(page)
      
          return render(request, 'template.html', {'items': items})
      
  2. Custom Pagination in Django:

    • Description: Customize pagination by creating a custom template for rendering pagination controls.
    • Code:
      # views.py
      from django.core.paginator import Paginator
      from django.shortcuts import render
      
      def custom_pagination(request):
          queryset = MyModel.objects.all()
          paginator = Paginator(queryset, 10)
      
          page = request.GET.get('page')
          items = paginator.get_page(page)
      
          return render(request, 'custom_template.html', {'items': items})
      
  3. Limiting Queryset in Django with Pagination:

    • Description: Use pagination to efficiently limit the number of database queries.
    • Code:
      # views.py
      from django.core.paginator import Paginator
      from django.shortcuts import render
      
      def limited_queryset_pagination(request):
          queryset = MyModel.objects.filter(some_condition=True)
          paginator = Paginator(queryset, 10)
      
          page = request.GET.get('page')
          items = paginator.get_page(page)
      
          return render(request, 'template.html', {'items': items})
      
  4. Django Paginate by n:

    • Description: Specify the number of items to display per page using the paginate_by attribute in a class-based view.
    • Code:
      # views.py
      from django.views.generic import ListView
      from .models import MyModel
      
      class PaginatedView(ListView):
          model = MyModel
          template_name = 'template.html'
          context_object_name = 'items'
          paginate_by = 10
      
  5. Django Paginated View:

    • Description: Use class-based views for paginated displays using the ListView class.
    • Code:
      # views.py
      from django.views.generic import ListView
      from .models import MyModel
      
      class PaginatedView(ListView):
          model = MyModel
          template_name = 'template.html'
          context_object_name = 'items'
          paginate_by = 10
      
  6. Adding Pagination to Django Views:

    • Description: Integrate pagination into your views to break down large data sets.
    • Code:
      # views.py
      from django.core.paginator import Paginator
      from django.shortcuts import render
      
      def paginated_view(request):
          queryset = MyModel.objects.all()
          paginator = Paginator(queryset, 10)
      
          page = request.GET.get('page')
          items = paginator.get_page(page)
      
          return render(request, 'template.html', {'items': items})