0% found this document useful (0 votes)
17 views

Create Blog Post Models With Django 3.1 - Django Tutorial 2020

This document provides instructions for creating a blog post model in Django to allow adding authors, categories, and blog posts. It defines models for Author, Category, and Post, with fields like title, slug, content, and relationships between models. It also shows configuring the admin interface to manage the models, running migrations to add them to the database, and creating a superuser account.

Uploaded by

Mario Colosso V.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Create Blog Post Models With Django 3.1 - Django Tutorial 2020

This document provides instructions for creating a blog post model in Django to allow adding authors, categories, and blog posts. It defines models for Author, Category, and Post, with fields like title, slug, content, and relationships between models. It also shows configuring the admin interface to manage the models, running migrations to add them to the database, and creating a superuser account.

Uploaded by

Mario Colosso V.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

!"#$%&'()"**+,%$ /012#02 ?(.#*.4).

(;

!"#$%&&%'()* +,%-. $%&&%'

/012#02#.%#3%-)#455%-2.#6$-../0..1-2$7#8%)#3%-)#9()*%24&0:(;#(<9()0(25(=

/012#02#'0.>#?%%1&( Not you? Sign in or create an account

3*"+4"&5#20&6274&82)"#7
9%4,&:;+<02&=1>&?&:;+<02
@A42*%+#&BCBC
/(&@0#+,;())4>0@ A(5#BC#"D"D · E#@02#)(4;

In this article, we will see how to create a post model for our blog
website. where we can add authors for our website, di8erent
categories of our posts, and all stu8 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.
!"#$%#&'&(#)&'**
So, the Brst 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 Ble.
# Application definition

INSTALLED_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 Ble, 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 Ble in the blog app:


#blog/urls.py

from django.urls import path


from blog.views import blog
urlpatterns = [
path("", blog, name='blog'),
]

Now, in the views Ble, we will create a simple function view to


render to the blog page.

from django.shortcuts import render

def blog(request):
context = {}

return render(request, "blog/blog.html", context)

!"#$%#&%+#&,-.#/0
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

1+$%&)#&.2.&+#"#3
We start with deBning 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 deBne 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
6eld module, it allows us to create a slug Beld 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 Ble.

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 Beld, which
means there’s no character limit.
And we need date Beld 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 Beld too as well as the
overview Beld.

We need to add an author for our post too. Here, we created a


relationship on a model that has not yet been deBned. The
foreign-key Beld is used to link to other model classes, which is
Author in our case.

In the Author’s class, the user, which will be onetooneBeld 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 Beld to this model, so each other can
have its proBle 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 Beld too, to choose whether our post
will be a draft or we can publish it.

4.2%&$.,256*7&82/#
now, to add, edit and delete the posts, authors, or categories
we’ve just created in the models Ble, we will add them to the
admin.py Ble.

from django.contrib import admin


from blog.models import Category, Author, Post

admin.site.register(Author)
admin.site.register(Category)
admin.site.register(Post)
!-59/:02-5;
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 Ble 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

AF421% AF421%#$)4@('%)G H3.>%2#H)%1)4@@021 H3.>%2I J(,#A(K(&%9@(2.

+,%-. L(&9 M(14&

You might also like