Write Models
There is a file named models.py in our app directory (blog).
Let's Create models for Blog and Comment.
What about a User model?
We don't need to write our own User model. Django ships with a complete authentication system (django.contrib.auth) that already provides a User model with username, email and a securely hashed password. Writing a custom user table that stores a plain-text password would be extra work and a serious security flaw, so we will use the built-in one.
Never store or compare passwords in plain text. Django's built-in User model hashes the password automatically when you create users through User.objects.create_user() or through UserCreationForm (we will use both concepts later in this series).
Blog and Comment Models
Add following code in your blog/models.py.
from django.conf import settings
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True)
time = models.TimeField(auto_now_add=True)
image = models.ImageField(upload_to="blog/images", default="")
class Comment(models.Model):
comment = models.TextField()
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True)
time = models.TimeField(auto_now_add=True)
blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
settings.AUTH_USER_MODEL points to the active user model (by default django.contrib.auth.models.User). Referencing it in a ForeignKey instead of importing the User class directly is the recommended practice — if the project ever switches to a custom user model, these models keep working without changes.
Run Migrations
Models only describe the tables — the database doesn't know about them yet. Generate the migration files for the blog app and apply them:
python manage.py makemigrations blog
python manage.py migrate
makemigrations bloginspects the models above and writes migration files intoblog/migrations/.migrateapplies those migrations (plus Django's own, including the auth tables forUser) to the database.
Run these two commands again whenever you change anything in models.py. If you skip this step, any view that touches the database will fail with an "no such table" error.