How to create a simple blog using Django 3 - part 3

/ #Django

In the third part of this series I'm going to show you how to setup the database models and how to fill them with some dummy data.

Setting up the model

In the previous part of this series we created the blog app where most of the functionality for this blog will be. Now we're going to set up the database model where we describe how the data is stored in the database.

Open up "blog/" in your editor and add the following code:

class Category(models.Model):
	title = models.CharField(max_length=255)
	slug = models.CharField(max_length=255)
	description = models.TextField(blank=True, null=True)
	class Meta:
		ordering = ('title',)
	def __str__(self):
		return self.title

class Post(models.Model):
	DRAFT = 'draft'
	PUBLISHED = 'published'
		(DRAFT, 'Draft'),
		(PUBLISHED, 'Published')
	categories = models.ManyToManyField(Category, related_name='posts')
	title = models.CharField(max_length=255)               
	slug = models.CharField(max_length=255)                
	intro = models.TextField()  
	body = models.TextField()
 	status = models.CharField(max_length=15, choices=CHOICES_STATUS, default=PUBLISHED)
 	created_at = models.DateTimeField()
	class Meta:
		ordering = ('-created_at',)
	def __str__(self):
		return self.title

This is everything we need for now. We're going to expand this with some more model functions and also add one more model for the comments in a later part of the series.

The first model is for the "Category". On my blog, you can see them to the right and they are used to divide my posts into the correct category.

The title field is quite self explainable. It's where we store the title of the category. We also added another CharField (a field to store short sentences) for the slug or the address if you like.

We also need a description field, but this is set to be "blank=True, null=True" which means that it's not required to fill it out.

Under the fields, we added a class called Meta. This can be helpful for setting information like the ordring, different plural name for the model and so on.

The last function "__str__" isn't strictly necessary, but I always use to add it because it's so much easier to view the objects in the Django admin interface.

The post model

The model for our posts are a little bit more complicated. First we create a couple of constants, these are used to set the status for our posts. I'll explain later why I solved it this way.

The first field is a "ManyTomanyField", this means that every post can have multiple categories.

Updating the database

Now that the most necessary models are defined, we can use Django to generate the SQL tables.

We only need to make one more change to the code first, so that Django knows that the "blog" app exists. Open up "myblog/" in your editor, and add "blog" to the list of installed apps like this:


Now we're ready to up our command line, go to the root of our application and type the following command:

$ python makemigrations

This will tell Django to create migrations file for the database. This way, Django will know what to add to the database, what to change and what to delete.

After that, run this command:

$ python migrate

This will tell Django to run the migrations file and the database will be up to the with the models we created.

Adding data to the database

We are going to use a shell to add data directly in to the database. Run the following command to start:

$ python shell

When the shell has started, we have access to all of Django's functionality. First, we need to import the Category model and the Post model.

>>> from blog.models import Category, Post

Now we actually have the ability to get and set information to both of those models. Let's start by creating a category:

>>> cat1 = Category.objects.create(title='Category 1', slug='category-1', description='This is the description of the first category')

To verify that the category was created, just write "cat1" on the next line and hit enter. Hopefully, you should see something like this:

<Category: Category 1>

Nice :-)

Before we call it a wrap for the day, let's just add one post too.

>>> post1 = Post(title='Post number 1', slug='post-number-1', intro='This is the introduction', body='This is the body for post number 1')
>>> post1.categories.add(cat1)

As you can see, this is a little bit different than when you created the category. Instead of "MODEL.objects.create(", we just use "MODEL(", this is because it makes it able to create the object without saving it to the database.

This is necessary, because of the ManyToManyField with the Category. On the second line, we run an "add" command to the categories field where we add the category we just created and then we save it.


I hope you don't feel overwhelmed by all the command and stuff. Things will be better and you'll see things more clear as we go on with the blog.

In the next part of this series I'll show you how to start the Django admin interface where we also can add data to the database in a much simpler way :-)

How to create a simple blog using Django 3 series

Part 1 - Installation
Part 2 - File structure
Part 3 - Database models
Part 4 - Admin interface
Part 5 - Creating some templates
Part 6 - Views and URLs
Part 7 - Category views
Part 8 - Media files
Part 9 - Comments
Part 10 - Search


No comments yet...

Add comment

Subscribe to my newsletter