Tutorials  /  Python

How To Create Django Models

Ccentron Redaktion · January 2025 ·3 min read ·Python, Tutorial

Introduction

In the previous tutorial, “How To Create a Django App and Connect it to a Database,” we covered how to create a MySQL database, how to create and start a Django application, and how to connect it to a MySQL database.

In this tutorial, we will create the models that define the fields and behaviors of the Blog application data that we will be storing. These models map the data from your Django application to the database. It’s what Django uses to generate the database tables via their object relational mapping (ORM) API, referred to as “models.”

VM

Matching infrastructure at centron

Scripts and services eventually need an environment that keeps running: ccloud³ VMs from €3.12 per month, billed by the hour. Rent a cloud server →

Prerequisites to Create Django Models

This tutorial is part of the Django Development series and is a continuation of that series.

  • You have Django version 4 or higher installed.
  • You have connected your Django app to a database.
  • You are working with a Unix-based operating system, preferably an Ubuntu 22.04 cloud server.

Step 1 — Create Django Application

To be consistent with the Django philosophy of modularity, we will Create Django Models app within our project that contains all of the files necessary for creating the blog website.

Console
cd ~/my_blog_app
. env/bin/activate
cd blog
python manage.py startapp blogsite

Step 2 — Add the Posts Model

Open and edit the models.py file to contain the code for generating a Post model:

Python
from django.db import models
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User
from django.urls import reverse

class Post(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField(unique=True, max_length=255)
    content = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    author = models.TextField()

    def get_absolute_url(self):
        return reverse('blog_post_detail', args=[self.slug])
    
    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super(Post, self).save(*args, **kwargs)

    class Meta:
        ordering = ['created_on']

        def __unicode__(self):
            return self.title

Step 3 — Update Settings

Add the blogsite app to the INSTALLED_APPS section in settings.py:

Code
INSTALLED_APPS = [
    'blogsite',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Step 4 — Make Migrations

Create migration files for the models:

Console
python manage.py makemigrations

Apply the migrations to the database:

Console
python manage.py migrate

Step 5 — Verify Database Schema

Log into MySQL and verify that the tables were successfully created:

Code
SHOW TABLES;
DESCRIBE blogsite_comment;
DESCRIBE blogsite_post;

Conclusion about Create Django Models

In this tutorial, we’ve successfully added essential models for basic functionality in a dynamic blog web application. You’ve learned how to code models effectively, understand how migrations work, and the complete process of translating Django models into structured MySQL database tables. This knowledge ensures efficient database management and provides a strong foundation for building scalable web applications.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Python
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren