A Django Blog In VS Code — Posts Pagination & Quick DB Population

How To Create A Blog in VS Code — Part IX — DjangoSeries Episode # 12

J3
Jungletronics
6 min readFeb 17, 2022

--

Themes : PAGINATION & POST FILTERED

Let’s say that there are over 1600 users, 6000 Posts, and 330,000 rows in the DB.

It is fairly safe to say that if we are pulling down too many posts at once the model will probably take too long to load…think in each logo image…a large volume of unoptimized images is usually the most common reason behind website slowness.

This post deals just with the solution of this issue: PAGINATION.

We’ll learn how to create a page of POST FILTERED by a specific user as well.

Hurrah! That means our website isn't going to waste time loading a desktop-sized image and lots of posts for your mobile website.

Let’s get Started!

00#Step — This is a continuation of this post.

In that last post we deal with class-based views and DB’s crud operations.

01#Step — Let’s populate our database by adding more posts to our current application from a variety of different users.

That way we’ll have enough posts to see the pagination in action.

We will use a script inside Django Shell using a JSON file below:

[link to json file]

Paste this file inside your django_project root.

02 #Step— Now let’s use Django shell to load this posts:

(djangoEnv) C:\Users\giljr\new_django\django_project>python manage.py shell
Python 3.9.7 (default, Sep 16 2021, 16:59:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import json
>>> from blog.models import Post
>>> with open('posts.json') as f:
...
... posts_json = json.load(f)
...
>>> for post in posts_json:
... post = Post(title=post['title'], content=post['content'], author_id=post['user_id'])
... post.save()
...
>>> exit()

03#Step — run the server:

python manage.py runserver
We upload 24 posts to the database.
Now we can play with paginator…Let’s get on!

04#Step — Now let’s make a quick rundown of paginate.

We just want to show you a couple of things that we’re going to be using in order to loop over these pages whenever we use this on our site paginator.

(djangoEnv) C:\Users\giljr\new_django\django_project>python manage.py shell
Python 3.9.7 (default, Sep 16 2021, 16:59:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.core.paginator import Paginator
>>> posts = ['1','2','3','4','5']
>>> p = Paginator(posts, 2)
>>> p.num_pages
3
>>>
>>> for page in p.page_range:
... print(page)
...
1
2
3
>>> p1 = p.page(1)
>>> p1
<Page 1 of 3>
>>> p1.number
1
>>> p1.object_list
['1', '2']
>>> p1.has_previous()
False
>>> p1.has_next()
True
>>> p1.next_page_number()
2
>>> exit()

05#Step — Now Modify blog/views.py to include paginator:

...class PostListView(ListView):
model = Post
# context_object_name = 'object_list'
ordering = ['-date_posted']
paginate_by = 2
...

With that small change that will actually give us some pagination functionality so let’s see what we have so far so let’s pull back up the terminal here and I’m going to rerun that dev server.

06#Step —Let’s hard code the page request into the URL to get these other pages right now.

Just type in browser URL bar:

http://127.0.0.1:8000/?page=3
And magically you have paginator up and running \o/ As we have 28 post/2 = 14 pages
This is the last page…let’s confirm…
As you can see here…oops! 404! anytime you run out of pages and requests that page that doesn’t exist then you will get a 404 which is good!

Rather than manually typing them in to the URL bar like we’re doing it right now and our class-based view will be responsible for managing pagination.

07#Step —Modify blog\templates\blog\post_list.html, and add these script at the end:

Pagination script is inside {% if is_paginated %}…{% endif %} tags.

08#Step — run the server:

python manage.py runserver

Here is the result:

POSTS FILTERED— : Modus operandi V(iew) U(rls) T(emplate)

09#Step — V(iew):Modify your blog\views.py by creating another class:

CBV PostUserListView(ListView)
The difference between the old code is the creation of class PostUserListView(ListView) and some importations

10#Step — U(rls): GoTo blog\urls.py, and add these lines:

from blog.views import ... PostUserListViewurlpatterns = [
...
path('user/<str:username>/', PostUserListView.as_view(), name='post_list'),
...
]
The difference between the old code is the insertion of a new path.

11#Step — T(emplate): add 1 href in blog\post_detail.html, as below:

...
<div class="media-body">
<div class="article-metadata">
<a class="font-weight-bold mr-2" href="{% url 'post_list' object.author.username %}">{{ object.author }}</a>
...

12#Step — T(emplate): add 2 href and 1 class in blog\post_list.html, as below:

...
<div class="media-body">
<div class="article-metadata">
<a class="font-weight-bold mr-2" href="{% url 'post_list' object.author.username %}">{{ object.author }}</a>
<small ... </small>
</div class="mb-4">
<h1 class="display-6"><strong><a href="{% url 'post_detail' object.id %}">{{ object.title }}</a></strong></h1>
<br></br>
...
{% endfor %}
...
<<<< paginate script goes here see in step#07 >>>

13#Step — run the server:

python manage.py runserver

Here is the result:

The informational message appears every time you click on the author of the post. The filter worked!

That’s all Folks!

In the next episode Self-Service Django Password Reset.

See you around. Bye!

👉 git

References & Credits

Python Django Tutorial: Full-Featured Web App by Corey Schafer

Show a successful message with Class Based Views by stackoverflow.com

Related Posts

00#Episode — DjangoSerie — Django Intro — How To Build your First App in Python Django Framework — DjangoSeries

01#Episode — DjangoSerie — Django MTV In VS Code — How To Install Django Inside Virtual VS Code

02#Episode — DjangoSerie — Can You Solve This in Python? — Here is A Basic Python Question!

03#Episode — DjangoSerie — JUNGLE-DJANGO Webpage! This Is My New Django Netflix Clone Page!

04#Episode — DjangoSerie — A Django Blog In VS Code — Quick Start!Part_I

05#Episode — DjangoSerie — A Django Blog In VS Code — Database, Migrations & Queries — Part_II

06#Episode — DjangoSerie — A Django Blog In VS Code — Bootstrap, Tailwind CSS — Part_III

07#Episode — DjangoSerie — A Django Blog In VS Code — Forms & Validations — Part_IV

08#Episode — DjangoSerie — A Django Blog In VS Code — Login & Logout — Part_V

09#Episode — DjangoSerie — A Django Blog In VS Code — Upload Profile Picture — Part_VI

10#Episode — DjangoSerie — A Django Blog In VS Code — Update & Resize Picture — Part_VII

11#Episode — DjangoSerie — A Django Blog In VS Code — Class-Based-View & CRUD — Part_VIII

12#Episode — DjangoSerie — A Django Blog In VS Code — Posts Pagination & Quick DB Population — Part_IX (this one :)

13#Episode — DjangoSerie — A Django Blog In VS Code — Self-Service Django Password Reset — Part_X

14#Episode — DjangoSerie — A Django Blog In VS Code — Heroku Deploy — How To Push Your Site To Productio — Part_XI (this last one…whew!)

Here is the step-by-step —Django Unleashed by me o(* ̄▽ ̄*)ブ

--

--

J3
Jungletronics

😎 Gilberto Oliveira Jr | 🖥️ Computer Engineer | 🐍 Python | 🧩 C | 💎 Rails | 🤖 AI & IoT | ✍️