Creating a Django application and models

In this section, we will implement our blog application as well as a Django model called Post, which contains the object-oriented logic for the posts in our blog:

  1. First, in the manage.py panel, enter the following command:
manage.py@mysite > startapp blog
  1. This, as we have seen, will create a subfolder within our current project directory named blog with all the various Django-specific Python scripts for our blog application. Now, within the blog/models.py file, enter the following code (again, manually typing in the code is highly recommended):
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User


class Post(models.Model):
STATUS_CHOICES = {
('draft', 'Draft'),
('published', 'Published'),
}

title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250,
unique_for_date='publish_date')
author = models.ForeignKey(User, related_name='blog_posts',
on_delete=models.DO_NOTHING)
body = models.TextField()

publish_date = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,
choices=STATUS_CHOICES, default='draft')

class Meta:
ordering = ('-publish_date',)

def __str__(self):
return self.title

This Post class (which inherits from the models.Model class in Django) implements the model for our post objects.

While most of the preceding code is self-explanatory, there are a few things we should note within the model:

  1. Next, we need to register this new blog application with our main project. To do that, locate the INSTALLED_APPS list variable in the mysite/settings.py file and add the 'blog' string to that list. The variable should now look as follows:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog'
]
  1. Finally, we will apply the relevant migrations and create a corresponding database table for our new model. From the manage.py panel, run the following commands sequentially:
manage.py@mysite > makemigrations blog
manage.py@mysite > sqlmigrate blog 0001
manage.py@mysite > migrate

While executing these commands, you will see corresponding SQL statements being used to generate our table in the printed output of the manage.py panel. With everything executing successfully, our blog application has been officially created and set up.