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.
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.
logoi (logos), vlasnik (owner), naziv (name), boja (colour), oblik (shape: krug circle, kvadrat square, romb rhombus), napravljen (created), inicijali (initials).# 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()
| Field | Type | Meaning |
|---|---|---|
vlasnik | ForeignKey | a link to the user; on_delete=CASCADE – deleting a user also deletes their logos; related_name="logoi" makes user.logoi.all() possible |
naziv, slogan | CharField | text of limited length; blank=True – it can be empty |
boja | CharField + validator | only the #RRGGBB form is allowed |
oblik, font | CharField + choices | only values from the list – in a form it becomes a drop-down list |
napravljen | DateTimeField(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.
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.
# 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.
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})
| ORM | SQL (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 in Serbian with English subtitles – turn on subtitles (CC) in the YouTube player.
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.
For every task there is an example, instructions and a solution.
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.
makemigrations and then migrate. The error no such column means that a migration was forgotten.Logo.objects.get(...) raises an error if there is no result or there are several; for "maybe there is none" use filter(...).first().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?