Django: the Logo model, the database and the admin panel

Lesson 5 of 9 · Python web: Django project

For logos to be saved, Django has to know what one logo looks like: the name, the slogan, the colour, the shape, the font and who the owner is. We describe this with a model – a Python class from which Django makes a table in the database by itself. Then we add it to the admin panel and try out queries from Python.

Before you start: required knowledge – URLs and templates, functions in Python.
How to learn: work in your own project step by step and after every lesson check that the server works; do the task at the end on your own first. The code is for Django 5.2 (LTS) and Python 3.12+; write each part into the file named in the comment at the top of the example.
Names in the code: the names used throughout the project are in Serbian, as in the other lessons of the course: logoi (logos), vlasnik (owner), naziv (name), boja (colour), oblik (shape: krug circle, kvadrat square, romb rhombus), napravljen (created), inicijali (initials).

The Logo model

# logoi/models.py
from django.conf import settings
from django.core.validators import RegexValidator
from django.db import models


class Logo(models.Model):
    OBLICI = [("krug", "krug"), ("kvadrat", "kvadrat"), ("romb", "romb")]
    FONTOVI = [
        ("Arial, sans-serif", "Arial"),
        ("Georgia, serif", "Georgia"),
        ("'Courier New', monospace", "Courier New"),
    ]

    vlasnik = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="logoi")
    naziv = models.CharField(max_length=20)
    slogan = models.CharField(max_length=30, blank=True)
    boja = models.CharField(max_length=7, default="#dd0022",
                            validators=[RegexValidator(r"^#[0-9a-fA-F]{6}$", "The colour must be in the form #RRGGBB.")])
    oblik = models.CharField(max_length=10, choices=OBLICI, default="krug")
    font = models.CharField(max_length=40, choices=FONTOVI, default="Arial, sans-serif")
    napravljen = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-napravljen"]          # newest first

    def __str__(self):
        return f"{self.naziv} ({self.vlasnik})"

    def inicijali(self):
        """'Sekcija Pupin' -> 'SP', 'Logo' -> 'LO' (the same as in generator.js)."""
        reci = self.naziv.split()
        if not reci:
            return "?"
        if len(reci) == 1:
            return reci[0][:2].upper()
        return (reci[0][0] + reci[1][0]).upper()
FieldTypeMeaning
vlasnikForeignKeya link to the user; on_delete=CASCADE – deleting a user also deletes their logos; related_name="logoi" makes user.logoi.all() possible
naziv, sloganCharFieldtext of limited length; blank=True – it can be empty
bojaCharField + validatoronly the #RRGGBB form is allowed
oblik, fontCharField + choicesonly values from the list – in a form it becomes a drop-down list
napravljenDateTimeField(auto_now_add=True)the time is written only when the logo is created

Every model also gets an id field (a serial number, the primary key) automatically. The values in choices and the fields are the same as in the generator from the frontend project.

Migrations: from a class to a table

python manage.py makemigrations
python manage.py migrate

makemigrations compares the models with the state of the database and writes the change into logoi/migrations/0001_initial.py; migrate applies it to the database. When you change a model later (for example add a field), you repeat both commands. You do not write SQL by hand – but you can see it: python manage.py sqlmigrate logoi 0001.

The model in the admin panel

# logoi/admin.py
from django.contrib import admin
from .models import Logo


@admin.register(Logo)
class LogoAdmin(admin.ModelAdmin):
    list_display = ("naziv", "vlasnik", "oblik", "boja", "napravljen")
    list_filter = ("oblik", "napravljen")
    search_fields = ("naziv", "slogan", "vlasnik__username")

After this, /admin/ has a Logos table with columns, a filter by shape and date, and search. Add a few logos by hand – you will need them for the next steps.

The name looks nicer in the admin if you add verbose_name = "logo" and verbose_name_plural = "logos" to class Meta.

Queries from Python (ORM)

python manage.py shell
>>> from django.contrib.auth.models import User
>>> from logoi.models import Logo
>>> ana = User.objects.get(username="ana")
>>> Logo.objects.create(vlasnik=ana, naziv="Sekcija Pupin", boja="#1f5f91", oblik="romb")
<Logo: Sekcija Pupin (ana)>
>>> Logo.objects.count()
1
>>> ana.logoi.all()                                  # all of the user ana's logos
<QuerySet [<Logo: Sekcija Pupin (ana)>]>
>>> Logo.objects.filter(oblik="krug").count()       # WHERE oblik = 'krug'
0
>>> Logo.objects.filter(naziv__icontains="pupin")  # contains "pupin", ignoring capital letters
<QuerySet [<Logo: Sekcija Pupin (ana)>]>
>>> l = Logo.objects.first(); l.inicijali()
'SP'
>>> l.slogan = "We code"; l.save()                  # changing
>>> l.delete()                                      # deleting
(1, {'logoi.Logo': 1})
ORMSQL (roughly)
Logo.objects.all()SELECT * FROM logoi_logo
.filter(oblik="krug")WHERE oblik = 'krug'
.order_by("-napravljen")ORDER BY napravljen DESC
.create(...) / .save()INSERT / UPDATE
.delete()DELETE

The ORM (Object-Relational Mapping) turns Python expressions into SQL and always uses parameters – that is why it is resistant to the SQL injection from the lesson Security.

Video: the database in a Django application

Video in Serbian with English subtitles – turn on subtitles (CC) in the YouTube player.

A note about the video: the video was recorded for the first version of the project (an older version of Django, Heroku). The ideas are the same, but the code in this lesson differs in details – where they differ, the code on this page is the one that applies.

In the video the database is switched straight away to PostgreSQL installed on the computer. In this version of the project we stay with SQLite for development and use PostgreSQL only on the server.

Practice tasks

For every task there is an example, instructions and a solution.

TASK 01Difficulty: medium

A "favourite" field

Add the field omiljeni (favourite; yes/no, no by default) to the model, make and apply the migration, and show the field in the admin list, so that it can be changed directly in the list.

Common mistakes and tips
  • After every change of a model: makemigrations and then migrate. The error no such column means that a migration was forgotten.
  • Do not change tables in the database by hand – all changes go through models and migrations.
  • Logo.objects.get(...) raises an error if there is no result or there are several; for "maybe there is none" use filter(...).first().

Check your knowledge

Open the quiz

Models and the database

1. What does python manage.py makemigrations do?




2. What does related_name="logoi" in a ForeignKey mean?



3. Why is the ORM resistant to SQL injection?