How To Build a Blogging Platform using Python in Django

The project looks into how you can build a blogging platform for users to sign up and create their own blogs. It can be a good start for one to develop a platform for their user community to share ideas.

This will allow an organization to have an interactive way for allowing their users to share their ideas and thoughts or can also be developed further to a social media page or platform that allows users to post their thoughts.  

Intended audience: Who the article is for

This article targets python/Django developers who would want to build a web-based blogging application that allows its users to post their stories and others to read, it can be advanced to allow users to comment and rate other people’s posts.

Case Study: What the article is going to cover

It will cover building a web-based Django blogging system, for users to post stories and others to read their stories as well as allow users who created the stories to edit their stories.

The application is built using python programming language in Django Framework.

Requirements:

  1. Some knowledge of Python and Django
  2. Some knowledge about Bootstrap
  3. Knowledge on how to use gmail as an email client for your Django app
  4. Go through this article that shows you how to implement gmail as your Django email client

Getting started with the Web App

Creating a Django Project

  1. From your terminal navigate to the folder/location your project is to reside
  2. We will create a Django project called “blogProject”, type the command: django-admin startproject blogProject
  3. From the terminal navigate into the created project folder, where you will create and activate your project’s virtual environment by typing in the terminal the command “python –m venv venv”
  4. In windows, type “venv\Scripts\activate” in the terminal
  5. In Mac/Linux, type ”source venv/bin/activate” in the terminal
  6. After your virtual environment has been activated, run the code below in the terminal to install the following python packages
    • “pip install Pillow”: python package to be used in managing images
    • “pip install django” : python package to be used in building the web app
    • “pip install django-crispy-forms”  : to be used rendering bootstrap styles in HTML templates
  7. Create your first Django app by typing in the terminal the command: “python manage.py startapp blog”
  8. Create your second Django app by typing in the terminal the command: “python manage.py startapp users”
  9. Create a SQLite database that will used by the project by typing in the terminal the command: “python manage.py makemigrations”
  10. Apply database changes by typing in the terminal the command: “python manage.py migrate”
  11. Start your server by typing on the terminal the command: “python manage.py runserver”
  12. If the server starts successfully there should be a webpage up and running on the location: http://127.0.0.1:8000
  13. While in the terminal type Ctrl+C to stop the server
  14. Everything from now on will be performed inside this python activated environment

We are stopping the server so that we can create the database tables first and then apply the changes before restarting the server

Creating Project CSS File

  1. Open the Django project folder your code editor
  2. Open the “blog” app folder
  3. In the “blog” app folder, create a folder labelled “static”
  4. Inside the created “static” folder create another folder labelled “blog”
  5. Inside the “blog” folder just created inside the “static” folder, create a css file labelled “main.css”
  6. Copy the code below into the “main.css” file

Configure Django Project Settings

  1. Open your Django project folder: “blogProject”
  2. Locate a folder with a similar name to your Django project folder, this folder is in the same directory as your “blog” app folder
  3. Inside this folder is a python file labelled “settings.py”
  4. Open the “settings.py” file and locate the python variable ALLOWED_HOSTS, which is a python list located close to the start of the file
  5. Inside the ALLOWED_HOSTS enter the “localhost” URL created as well as the “127.0.0.1” URL, this is a security measure by Django to ensure that the web app can only be accessed via the set URLs. Below is an example of how to do so:
  1. Inside the “settings.py” file, locate the variable INSTALLED_APPS
  2. The variable installed_apps is a list where you will register the apps we just created
  3. Insert the code below inside the list:
  4. We also need to register the Django crispy form python package that we will use to beautify our HTML pages, inside the INSTALLED_APPS python list paste the code below:
  5. We also need to register the Django rest framework app that we will use to manage and create the project A.P.I.s, inside the INSTALLED_APPS python list paste the code below:
  6. We also need to inform crispy to use bootstrap 4 in its rendering of HTML elements, to do this paste the code below at the end/bottom of the settings.py file:
  7. Paste code below at the very end of the settings.py file,  this section assumes you already know or went through the article on how to configure Gmail as a Django email client:

Creating Blog Database Tables

  1. Open your Django project folder in your code editor
  2. Open the “blog” app folder
  3. We now create the database tables related to the “blog” app we created, which are:

Modules to be imported

The modules to be imported that will be used to build the database table are:

from django.db import models –  This will be used to convert a python class to a database table

from django.utils import timezone – This will be used to execute the “now“ method that returns the current date that will be used as default value when creating the date a post was made

from django.contrib.auth.models import User –  The default Django user database table

from django.urls import reverse – A method used to resolve a url name or lable into a URL

Post Table Logic

This table will hold the posts created. It will include the post title, content, date posted and author of the post. It will have the following fields:

title –This column will hold the title of the post with a maximum character length of 100

content –This column will hold the content to be posted inside a text field that can allow much more text data  

date_posted –This column will hold the date and time the post was created. It does so by using the DateTimeField and setting a default parameter of the current time to be saved once the post is created

author –This column will hold the foreign key that points to the specific user in the default User table provided for by Django.

__str__ –This is a method in the class “Post” class we will create that will be responsible for returning back the string representation of objects or table records created in the Post table. The string representation method will return is the title of the post

__repr__–This is a method in the class “Post” class we will create that will be responsible for returning back the object representation of the database object created in the Post table. The syntax of the object representation to be returned is “Post(title=’Blog One’, content=”Blog One Content”,author=user_instance)”

get_absolute_url –This is a method in the class “Post” class we will create that will be responsible for returning back the URL a user should be redirected to once a post is successfully created. The user should be redirected to the Post’s details page.  

To create the above “blog” tables in your project folder, navigate into the “blog” folder and open a file labelled “models.py” and paste the code below:

Creating User Database Tables

  1. Open your Django project folder in your code editor
  2. Open the “users” app folder
  3. We now create the database tables related to the “users” app we created, which is the profile table that will be used store the users profile pictures:

Modules to be imported

The modules to be imported that will be used to build the database table are:

from django.db import models –  This will be used to convert a python class to a database table

from django.contrib.auth.models import User –  The default Django user database table

from PIL import Image – The image class imported from the pillow library, which is referred to us “PIL”. This class is required when using the ImageField on a database column

Profile Image Table Logic

This table will hold a link to the specific user and a URL to their image. It will have the following fields:

user –This column will create a relationship with the profile image’s user

image – The profile image of the user

__str__ –This is a method in the class “Profile” class we will create that will be responsible for returning back the string representation of objects or table records created in the Profile table. The string representation method will return is the username of the user appended with the word “Profile”

To create the above “blog” tables in your project folder, navigate into the “blog” folder and open a file labelled “models.py” and paste the code below:

  

Create Database Signals

These are signals that will be raised when a particular database operation is performed

Creating Users Signals

These are signals that will be raised in the “users” app when a particular action is performed. We want users’ profiles to be created once any of them are created or registered. This action can be registered as a database signal.

To do this:

  1. Open the “users” app folder
  2. Locate/create a python filed labelled “signals.py” and paste the code below:

Modules to be imported

The modules to be imported that will be used to build the database table are:

from django.db.models.signals import post_save –  This is the signal that we will wait upon. When it is initiated we will perform the task we want e.g. create a default user profile

from django.contrib.auth.models import User –  The default Django user database table that will initiate the post save signal

from django.dispatch import receiver – The python method or function that will receive the signal generated and perform a set of actions or instructions.

from users.models import Profile – The database where will create a user profile entry related to the user just created,  the image used here will be the default image set on the database image column

Signals Logic

This file will have two methods, one to create a profile for a user just created and another to update the profile of a user if any of the user data is updated

  1. Within the same directory, locate a python file labelled “apps.py” and paste the code below:

Apply Database Changes

  1. In your terminal ensure you have activated your project’s virtual environment
  2. While in your projects activated virtual environment in your terminal
  3. Create database changes to be made by typing in the terminal the command: python manage.py makemigrations
  4. Apply database changes by typing in the terminal the command: python manage.py migrate

Create User Creation, Update and Profile Upload Forms

These are the forms used by the “users” app to register or create new users, update their user information and image profiles

  1. Open the “users” app folder
  2. Locate/create a python filed labelled “forms.py”
  3. Forms to be created are:
    • UserRegisterForm –  This form will use the following fields; ‘username’, ’email’, ‘password1’ and ‘password2’ and will be a form relying on the “User” database table model
    • UserUpdateForm –  This form will use the following fields; ‘username’ and ’email’ and will be a form relying on the “User” database table model
    • ProfileUpdateForm –  This form will use the following fields; ‘image’ and will be a form relying on the “Profile” database table model
  4. Paste the code below:

Creating your business logic for Users App

We will now create the business logic in the “views.py” file located in the “users” app folder. Below is how to do so:

  1. Open the “users” app folder
  2. Locate a python file labelled “views.py”
  3. Paste the code below:

Views Code Logic

We start by importing the following methods:

  • Render – This method is used to return a HTML page to the user
  • Redirect – This method is used to redirect the user back to the URL passed to it as an argument
  • messages – This is a Django built in method that can be used to send pop up messages from your views to the HTML pages
  • UserRegisterForm, UserUpdateForm and ProfileUpdateForm – The three user model forms we created
  • login_required – This is a python decorator method used on python function views to restrict a user to a view only if they have logged in, after which they will be redirected to the view

We now build the views/functions or methods below:

  • register – This is a method or function view that will display the UserRegisterForm on the register page for a user to enter the registration details, after which the same view will save the user date entered on the form if a user submits the form, which returns data back to the view using the POST request method. When a form is to be submitted the view will check if the form is valid, if so save the data, else inform user of detected errors.
  • profile – This is a method or function view that will display the UserUpdateForm and ProfileUpdateForm on the user profile page for a user to view their details as well as their profile picture.

It also allows a user to edit their details and upload a new profile picture if a user submits the form, which returns data back to the view using the POST request method. When a form is to be submitted the view will check if both forms are valid, if so save the data, else inform the user of detected errors.

Creating your business logic for the Blog App

We will now create the business logic in the “views.py” file located in the “blog” app folder. Below is how to do so:

  1. Open the “blog” app folder
  2. Locate a python file labelled “views.py”
  3. Paste the code below:

Views Code Logic

We start by importing the following methods:

  • Render – This method is used to return a HTML page to the user
  • get_object_or_404 – This method is used to get a specific object but returns a 404 error page if the object does not exist
  • CreateView – This is a Django built in class that can be used to create a database table entry by associating it with another class
  • UpdateView– This is a Django built in class that can be used to update a database table entry by associating it with another class
  • ListView – This is a Django built in class that can be used to return a list of records from a specified database table, hence converting the class inheriting from this class to a list view to be used on a HTML page
  • DeleteView – This is a Django built in class that can be used to delete a database record entry by associating it with another class, via inheriting from this class
  • Post – The blog database table or model we created
  • User – The built in Django ‘user’ database table
  • LoginRequiredMixin – The is a built in Django authentication function called a mixin that a python class based view will inherit whose function is to prevent a user from viewing the associated page unless they logged in
  • UserPassesTestMixin – The is a built in Django authentication function called a mixin that a python class based view will inherit whose function is to create a logic test that has to be passed else the page associated with the view is not loaded

We now build the views/functions or methods below:

  • Home – This is a method or function view that accepts a web request and returns back the index HTML page render and passes a list of posts to the page’s context
  • Post Detail View – This is a class based view or a class that inherits its functionalities from django’s built in “DetailView” class. In this class we have to specify the model or database table the class will work with which is the “Post”. A primary key denoted as “pk” is passed to this class so as to fetch the specific post details that will be displayed a form on a HTML page
  • Post List View – This is a class based view or a class that inherits its functionalities from another class view, in this case django’s built in “ListView” class. In this class we have to specify the model or database table the class will work with which is the “Post” and the template that will render the data.

We will also specify the context object name that the HTML page will use to access the posts data records, we instruct the database to load the data starting with the latest and to paginate the data by showing five records per page.

  • User Post List View – This is a class based view or a class that inherits its functionalities from another class view, in this case django’s built in “ListView” class. In this class we will display the posts related to a specific user by passing the username.

The syntax is the same as the Post List View but the only difference is that we have to override a built-in ListView method called ‘get_queryset’ that is used to return the data that is to be displayed to the HTML page. Within this method we use the passed username parameter, to get the associated user and return posts related to this specified user

  • Post Delete View – This is a class based view or a class that inherits its functionalities from another class view, in this case django’s built in “DeleteView” class. It will also inherit from mixin classes “LoginRequiredMixin”, “UserPassesTestMixin”, to ensure that a user has to log in and also be the author of the post to be deleted.

In this class we have to specify the model or database table the class will work with which is the “Movies”, set a success URL which is the URL a user is to be redirected to after successful data deletion and the template that will render the data.

  • Post Update View – This is a class based view or a class that inherits its functionalities from another class view, in this case django’s built in “UpdateView” class. It will also inherit from mixin classes “LoginRequiredMixin”, “UserPassesTestMixin”, to ensure that a user has to log in and also be the author of the post to be updated.

In this class we have to specify the model or database table the class will work with which is the “Movies”, the fields it’s to work with, which is the ‘name’ field, the template that will render the data/form.

  • About – This is a method or function view that accepts a web request and returns back the blog’s about HTML page

Creating “users” HTML Templates

  1. On these HTML templates is where the different user data will be displayed
  2. We will start by creating HTML templates related to the “users” app we created, which are:
    • login.html – The log in page
    • logout.html – The log out page
    • register.html – The register or sign up page
    • profile.html – The user profile page
    • password_reset.html – The page a user will input their email for a password reset link to be sent to
    • password_reset_complete.html – The page that will notify a user that a password reset link has been successfully sent to the provided email address
    • password_reset_confirm.html – This page where a user will enter their new password
    • password_reset_done.html – This page will be used to display to the user the success message after the password has been changed
  3. To create the above “users” HTML templates do the following:
    • In your project folder navigate into the “users” folder
    • Create a folder labelled “templates”
    • Inside the “templates” folder create another folder and label it “users”
    • Inside the “users” folder you have just created inside the “templates” folder
    • Create the following blank HTML pages; login.html, logout.html, register.html, profile.html, password_reset.html, password_reset_complete.html, password_reset_confirm.html, password_reset_done.html and send_email.html.
    • Below is a screenshot of the “users” directory tree:

  1. Below are the HTML codes to be placed on each HTML page

Creating “blog” HTML Templates

  1. On these HTML templates is where the different blog data will be displayed
  2. We will start by creating HTML templates related to the “blog” app we created, which are:
    • home.html – The default home page for the web app with brief instructions on how the web app works
    • base.html – This is the page that will be inherited/extended by all other HTML template pages
    • about.html – This is the page that will display the blog about details
    • post_confirm_delete.html – This is the page to be used for asking a user to confirm that they want to delete a specific data record
    • post_detail.html – This page will be used to display the details of a post
    • post_form.html – This page will be used to display a form for a post to be created or updated
    • user_post.html – This page will be used to display a list of all posts related to a specific user
  3. To create the above “blog” HTML templates do the following:
    • In your project folder navigate into the “blog” folder
    • Create a folder labelled “templates”
    • Inside the “templates” folder create another folder and label it “blog”
    • Inside the “blog” folder you have just created inside the “templates” folder
    • Create the following blank HTML pages; about.html, base.html, home.html, post_confirm_delete.html, post_detail.html, post_form.html and user_post.html.

5. Below is a screenshot of the “blog” directory tree:

  1. Below are the HTML codes to be placed on each HTML page

Creating the “blog” App URLs

These are the URLs that will be used by the user to navigate the “blog” web app. They are usually placed in a file called “URLs.py”. Do the following to create/edit this file:

  1. Open the “blog” app folder
  2. Locate/create a python file labelled “URLs.py”
  3. Paste the code below:

Creating the “users” App URLs

These are the URLs that will be used by the user to navigate the “users” web app. They are usually placed in a file called “URLs.py”. Do the following to create/edit this file:

  1. Open the “users” app folder
  2. Locate/create a python file labelled “URLs.py”
  3. Paste the code below:

Configure Project URLs

This is where the URLs that point to each Django app are placed so that they are accessible from a browser. They are usually placed in a file called “URLs.py”. Do the following to create/edit this file:

  1. Open your Django project folder: “blogProject”
  2. Locate a folder with a similar name to your Django project folder, this folder is in the same directory as your “blog” app folder
  3. Open the “blogProject” folder that is inside you Django project folder
  4. Locate/create a python file labeled “URLs.py”
  5. Paste the code below:

Project Tree

Below is a screenshot of how your project tree should look like, assuming the name of your Django project is “blogProject”:

    

Run the server

  1. cd/navigate into the “blogProject” Django project via the terminal
  2. Activate the virtual environment by typing the command: “venv\Scripts\activate”
  3. Start the server by typing the command: python manage.py runserver
  4. If there’s nothing wrong, the server should be up on http:127.0.0.1:8000

Testing the System

  1. Once the server is up
  2. Go to the web page address e.g. http://127.0.0.1:8000
  3. Follow the instructions on the about page on how to test the system

NB: Remember to navigate to this tutorial here to learn how to integrate a Gmail as an email client for your Django project. The credentials retrieved from Gmail are to be placed in the project settings file.

Conclusion

You should now have a basic understanding of how to create a blogging application that can be used by your users to share information as well as a good building block for creating a social media platform.

Further improvements could be done on the project such as allowing users to like, share or comment on other user’s posts

Finally, you can find the code snippets in this @repo.

Quick Guide

If you just want to clone the project and get it up running, below is how to do so in minutes:

  1. Clone it:
    • git clone https://bitbucket.org/dans0l/blogProject.git
  2. Cd into it:
    • cd blogProject
  3. Create a venv:
    • python3 -m venv venv
  4. Activate venv:
    • Mac/Linux: source venv/bin/activate
    • Windows: venv\Scripts\activate
  5. Install the requirements:
    • pip install -r requirements.txt
  6. Create DB
    • python manage.py makemigrations
  7. Apply DB Changes:
    • python manage.py migrate
  8. Run the server:
    • python manage.py runserver
  9. Navigate to the site: http://127.0.0.1:8000
  10. Follow the instructions on the about page to start using the site

Please let me know how your experience was, Thank you.

1 Shares:
You May Also Like