![]() |
VOOZH | about |
Pagination system is one of the most common features in blogs, search engine , list of result etc. Seeing the popularity of pagination system django developers have build a Paginator class so that web developers do not have to think of the logic to make paginators.
The Paginator class is located in django/core/paginator.py. It helps divide a list of objects into pages, making it easy to display a subset of objects per page.
To use the paginator, import it along with some exceptions from Django:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
p = paginator(list_of_objects, no_of_objects_per_page)
Optional Arguments:
Prerequisites:
If you don’t have a Django project or app yet, create them:
django-admin startproject myproject
cd myproject
python manage.py startapp blog
In your app’s models.py, define the Post model if not already done:
Run the following commands to create the database table:
python manage.py makemigrations
python manage.py migrate
You can add posts via the Django admin or shell:
python manage.py shell
Then inside the shell:
from blog.models import Post
Post.objects.create(title="Post 1", author="Author 1", content="Content 1")
Post.objects.create(title="Post 2", author="Author 2", content="Content 2")
# ... create at least 8 posts as in the example
Exit the shell with exit().
In your app’s views.py, add the pagination code:
Create a folder named templates inside your app folder (blog/templates/) and inside it create index.html.
Add this template content:
In your app, create (or edit) urls.py (blog/urls.py):
Then include your app’s URLs in the project’s main urls.py (myproject/urls.py):
Start the Django development server:
python manage.py runserver
Output:👁 Image
In the image we have send the value of the page number with a GET request ( denoted with rectangle). You can see the pagination in the bottom of the image ( marked with rectangle ).
Here is another image of the last page: