Django Pagination-Simple than any Framework

Django Pagination

I am in love with Django. Of course, it is not my best framework, but the simplicity of some tasks makes it awesome. Some factors like authentication, forms, pagination require just few code lines and you are ready to go.

Whenever you want to learn a framework in the best way, read the documentation first. Pagination is the bottom numbers or words that contain links directing y9ou to the next page. Most commonly used when we want to increase the loading speed of a site. You don’t need to load all the content (especially images), they take a lot of bytes downloading, hence slowing the site down. And that is how the idea of pagination was invented.

First, after creating your content on the site. In the view.py, just below the main class, which contains the content to be displayed, add paginate_by=x. The value of X is the number of items required on a single page.

class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 5

Go inside your HTML file, let's say home.html then set up some buttons for first, last, next, and previous which are common.

Let us discuss each line of the cover image-Kindly look at the image to get clear view.:

Line 1
Confirm if this page is paginated. If you indicated ‘paginated by’ in views.py then it will set the Boolean to true.

Line 2
This line confirms if there is a previous page so that it can display the previous link, if not it hides.

Line 3
If there is a previous page then it will display the first-page link to direct you back to the first content.

Line 4
If there is a previous, then this link directs to the previous page.

Line 5
This tag closes the if page_obj.has_previous

Line 6
This line confirms if there is the next page. For the last page, this will be set to false and the following links won't be displayed (Next and Last).

Line 7
This link directs the user to the next page.

Line 8
This link will total the number of pages and open the last page.

Line 9
The line terminates the testing of has_next.

Line 10
This line terminates the Pagination test

Happy Django coding.

17