Create Blog Post Models With Django 3.1 — Django Tutorial 2020

Selmi Abderrahim
5 min readDec 8, 2020

In this article, we will see how to create a post model for our blog website. where we can add authors for our website, different categories of our posts, and all stuff related to the blog post.

As you see here, I’m working on Windows this time, I’m using Vscode for this tutorial. And we have here our project with everything installed and ready to go.

Create A New App

So, the first thing I’ll do is to make sure our virtual env is activated.

(env) PS C:\Users\Cisco\ ...

Then creating a new app, it’s a good practice to keep applications separate inside our Django project.

> python manage.py startapp blog

Next, we will tell Django to use this app, by adding it to the installed apps list in the settings.py file.

# Application definitionINSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'pages',
'blog', #new
]

In the project folder, We will include the blog URLs file, this way, Django will redirect everything that comes into ‘http://127.0.0.1:8000/blog' to blog.urls and looks for instructions from there.

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("pages.urls")),
path("blog/", include("blog.urls")), #new
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #For media files

We need to create the urls.py file in the blog app:

#blog/urls.pyfrom django.urls import path
from blog.views import blog
urlpatterns = [
path("", blog, name='blog'),
]

Now, in the views file, we will create a simple function view to render to the blog page.

from django.shortcuts import renderdef blog(request):
context = {}
return render(request, "blog/blog.html", context)

Create the models

Okay, we are ready to create our model:

from django.db import models
from autoslug import AutoSlugField
from django.contrib.auth import get_user_model
User = get_user_model()class Author(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_image = models.ImageField(upload_to="")
def __str__(self):
return self.user.username
class Category(models.Model):
title = models.CharField(max_length=20)
def __str__(self):
return self.title
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
class Post(models.Model):
title = models.CharField(max_length=200)
slug = AutoSlugField(populate_from='title')
overview = models.TextField()
date = models.DateTimeField(auto_now_add=True)
content = models.TextField()
author = models.ForeignKey(Author, on_delete=models.CASCADE)
categories = models.ManyToManyField(Category)
published = models.BooleanField()
def __str__(self):
return self.title

What we did here?

We start with defining our model object, we give it a simple name, Post.

models.Model here to tell Django to save our model in the database.

Then we define the properties of our class, for sure we need a title for our blog post, it will be a CharField with a limit of 200 characters.

For the slug, instead of adding it manually like the title or creating a method to save it, we can use the Django auto slug field module, it allows us to create a slug field in just one line of code.
So we need to install it using pip.

> pip install django-autoslug

Then add this line to the top of the file.

from autoslug import AutoSlugField...slug = AutoSlugField(populate_from='title')

And we use it this way, and the populate from to create a slug based on that title.

Also, we can add an overview for the post, it will give the readers a taste or teaser of a full blog post and it will be a text field, which means there’s no character limit.

And we need date field to show readers and visitors when we created that post. With the option of auto_now_add set to True, which means the data will be added automatically the moment you create the post.

For the content, we will use the text field too as well as the overview field.

We need to add an author for our post too. Here, we created a relationship on a model that has not yet been defined. The foreign-key field is used to link to other model classes, which is Author in our case.

In the Author’s class, the user, which will be onetoonefield to get only one user.
For that, we will import the get_user_model from the django.contrib; This is how we will reference the user model, using django.contrib.

We will also add an image field to this model, so each other can have its profile picture.
We added the upload to option, in case you want to save images you upload in other location instead of our default media folder.

And to handle images in Django we need to install Pillow, using this command line:

> pip install pillow

And we use the str method here to convert objects into a strings, which means, in the admin page, instead of a list of objects, we will see a list of usernames, which is more readable I guess.

It’s optional, but I want to add categories to my Post, It will take a ManyToManyField, which means we can choose more than one category for our post.

And for that, I’ll create a model class for the Category, it will hold a title with a max of 20 characters.
Again the str method to display the title instead of the category object.

I think we can add a boolean field too, to choose whether our post will be a draft or we can publish it.

Edit admin.py file

now, to add, edit and delete the posts, authors, or categories we’ve just created in the models file, we will add them to the admin.py file.

from django.contrib import admin
from blog.models import Category, Author, Post
admin.site.register(Author)
admin.site.register(Category)
admin.site.register(Post)

Conclusion:

So, everything is ready now, The last thing we will do is adding our models to our database. We will let Django save the changes of our models.
using:

> python manage.py makemigrations

Then we have a migration file to apply to our database, type

> python manage.py migrate

After that we create a superuser account to login to our admin page.

> python manage.py createsuperuser

Run the server.

> python manage.py runserver

Let’s login.

As you see here, this is the admin dashboard, here we can add, edit, or delete our posts.

Watch tutorial on Youtube: https://youtu.be/6GnVAWVWJso

--

--

Selmi Abderrahim

I’m a computer science student. I do freelancing in my free time. I am a big fan of affiliate marketing, it helped me a lot to monetize my daily stuff.