Creating an application in Django

Let’s create your first Django application. I am going to show you how to create a blog App. From your project’s root directory, run the following command:

python3 manage.py startapp blog

admin.py : This is where you register models to include them into the Django administration site. Using the Django admin site is optional.

migrations : This directory will contain database migrations of your application. Migrations allow Django to track your model changes and synchronize the database accordingly.

models.py : Data models of your application. All Django applications need to have a models.py file, but this file can be left empty.

tests.py : This is where you can add tests for your application.

views.py : The logic of your application goes here. Each view receives an HTTP request, processes it, and returns a response.

Designing the blog data schema

I am going by defining the initial data models for our blog. A model is a Python class that subclasses django.db.models.Model , in which each attribute represents a database field. Django will create a table for each model defined in the models.py file. When you create a model, Django offers you a practical API to query the database easily.

First, I will define a Post model. Open the models.py file of the blog application and you can define your on blog model. Here is the code I am using. Which I have learned from some books.

How models.py look before adding the code. I am using the Atom (You can use any text editor.)

Let’s take a look at the fields we just defined for this model:

title : This is the field for the post title. This field is CharField , which translates into a VARCHAR column in the SQL database.

slug : This is a field intended to be used in URLs. A slug is a short label containing only letters, numbers, underscores, or hyphens. We will use the slug field to build beautiful, SEO-friendly URLs for our blog posts. We have added the unique_for_date parameter to this field so we can build URLs for posts using the date and slug of the post. Django will prevent from multiple posts having the same slug for the same date.

author : This field is ForeignKey . This field defines a many-to-one relationship. We are telling Django that each post is written by a user and a user can write several posts. For this field, Django will create a foreign key in the database using the primary key of the related model. In this case, we are relying on the User model of the Django authentication system. We specify the name of the reverse relationship, from User to Post , with the related_name attribute.

body : This is the body of the post. This field is TextField , which translates into a TEXT column in the SQL database.

publish : This datetime indicates when the post was published. We use Django’s timezone now method as default value. This is just a timezone-aware datetime.now .

created : This datetime indicates when the post was created. Since we are using auto_now_add here, the date will be saved automatically when creating an object.

updated : This datetime indicates the last time the post has been updated. Since we are using auto_now here, the date will be updated automatically when saving an object.

status : This is a field to show the status of a post. We use a choices parameter, so the value of this field can only be set to one of the given choices.

The class Meta inside the model contains metadata. We are telling Django to sort results by the publish field in descending order by default when we query the database. We specify descending order by using the negative prefix.

Since we are going to deal with datetimes, we will install the pytz module. This module provides timezone definitions for Python and is required by SQLite to work with datetimes. Open the shell and install pytz with the following command:

pip3 install pytz

Django comes with support for timezone-aware datetimes. You can activate/ deactivate time zone support with the USE_TZ setting in the settings.py file of your project. This setting is set to True when you create a new project using the start project management command.

Activating your application

In order for Django to keep track of our application and be able to create database tables for its models, we have to activate it. To do this, edit the settings.py file and add blog to the INSTALLED_APPS setting. It should look like this:

Creating and applying migrations

Let’s create a data table for our model in the database. Django comes with a migration system to track the changes you do to your models and propagate them into the database. The migrate command applies migrations for all applications listed in INSTALLED_APPS ; it synchronizes the database with the current models and migrations.

First, we need to create a migration for the new model we just created. From the root directory of your project, enter this command:

python3 manage.py makemigrations blog

Django just created a file 0001_initial.py inside the migrations directory of the blog application. You can open that file to see how a migration looks like.

Let’s take a look at the SQL code that Django will execute in the database to create the table for our model. The sqlmigrate command takes migration names and returns their SQL without running it. Run the following command to inspect its output:

python3 manage.py sqlmigrate blog 0001

The exact output depends on the database you are using. The output above is generated for SQLite. Django creates a primary key automatically for each model but you can also override this specifying primary_key=True on one of your model fields.

Let’s sync our database with the new model. Run the following command to apply existing migrations:

python3 manage.py migrate

If you edit your models.py file in order to add, remove, or change fields of existing models, or if you add new models, you will have to make a new migration using the makemigrations command. The migration will allow Django to keep track of model changes. Then you will have to apply it with the migrate command to keep the database in sync with your models.

Leave a Reply