Part 5 - Models and Database

Creating a Django model 
Django uses ORM (Object-Relational Mapping), which allows us to define a database table using a Python class.

from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=200)
    subtitle = models.CharField(max_length=300, blank=True)
    image = models.ImageField(upload_to='articles/', blank=True, null=True)
    content = models.TextField()
    date = models.DateTimeField('Publication Date', auto_now_add=True)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return self.title
pip install Pillow

Migrations
After creating or editing models, Django needs to generate and apply migrations. Small files that describe the changes to your database structure.

python manage.py makemigrations
python manage.py migrate

makemigrations → creates migration files based on your model changes.
migrate → applies those migrations to the database, creating or updating tables as needed.
 

Displaying the models in the Django admin interface

from django.contrib import admin
from .models import Article

admin.site.register(Article)


Access through the browser:
http://localhost:8000/admin


Tested with Django 5.2



09 Sept. 2024 | Last Updated: 09 Jan. 2026 | jaimedcsilva

Related
  • Part 1 - Virtual Environment
  • Part 2 - Setting up a Django Project
  • Part 3 - Templates, Views and URLs
  • Part 4 - Static and Media Files
  • Part 5 - Models and Database
  • Part 6 - Connecting everything
  • Part 7 - Publishing to the internet

  • Buy Me a Coffee