Editing a saved logo
Add the page /moji-logoi/<pk>/edit/ on which a user changes their logo in the generator (the form filled in with the existing values) and an "Edit" button on the card in "My logos".
We put everything together: the generator from the frontend project becomes a Django form, a signed-in user saves a logo to the database, on the "My logos" page sees all their logos drawn on the server and can delete them – but only their own.
# logoi/forms.py
from django import forms
from .models import Logo
class LogoForm(forms.ModelForm):
class Meta:
model = Logo
fields = ["naziv", "slogan", "boja", "oblik", "font"]
widgets = {
"naziv": forms.TextInput(attrs={"class": "form-control", "maxlength": 20}),
"slogan": forms.TextInput(attrs={"class": "form-control", "maxlength": 30}),
"boja": forms.TextInput(attrs={"type": "color", "class": "form-control form-control-color w-100"}),
"oblik": forms.Select(attrs={"class": "form-select"}),
"font": forms.Select(attrs={"class": "form-select"}),
}
ModelForm makes the form fields from the model fields: choices become drop-down lists, the colour validator checks the input, and max_length the length. With widgets we give the fields Bootstrap classes and the type color for choosing a colour. (The model fields are naziv = name, boja = colour, oblik = shape.)
# logoi/views.py (the final version – lesson 8)
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import redirect_to_login
from django.shortcuts import get_object_or_404, redirect, render
from .forms import LogoForm
from .models import Logo
def naslovna(request):
return render(request, "logoi/naslovna.html")
def generator(request):
if request.method == "POST":
if not request.user.is_authenticated: # saving only for signed-in users
return redirect_to_login(request.get_full_path())
form = LogoForm(request.POST, auto_id="%s")
if form.is_valid():
logo = form.save(commit=False) # the object is not in the database yet
logo.vlasnik = request.user # the owner is set by the server, not by the form
logo.save()
messages.success(request, f"The logo \"{logo.naziv}\" has been saved.")
return redirect("moji_logoi")
else:
name = request.GET.get("naziv", "Logo")[:20]
form = LogoForm(initial={"naziv": name}, auto_id="%s")
return render(request, "logoi/generator.html", {"form": form})
@login_required
def moji_logoi(request):
logos = request.user.logoi.all() # related_name="logoi" from the model
return render(request, "logoi/moji_logoi.html", {"logos": logos})
@login_required
def obrisi(request, pk):
logo = get_object_or_404(Logo, pk=pk, vlasnik=request.user) # someone else's logo -> 404
if request.method == "POST":
logo.delete()
messages.info(request, "The logo has been deleted.")
return redirect("moji_logoi")
return render(request, "logoi/obrisi.html", {"logo": logo})
# logoi/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.naslovna, name="naslovna"),
path("generator/", views.generator, name="generator"),
path("moji-logoi/", views.moji_logoi, name="moji_logoi"), # lesson 8
path("moji-logoi/<int:pk>/obrisi/", views.obrisi, name="obrisi"), # lesson 8
]
| Detail | Why |
|---|---|
auto_id="%s" | the fields get the ids naziv, boja… (instead of id_naziv) – the same as in generator.js, so the JavaScript works without changes |
save(commit=False) + logo.vlasnik = request.user | the owner is not chosen in the form – otherwise a user could save a logo "in someone else's name" |
redirect_to_login | a user who is not signed in and clicks "Save" goes to the sign-in page and then comes back to the generator |
get_object_or_404(Logo, pk=pk, vlasnik=request.user) | someone else's logo gives a 404 error, as if it did not exist |
| deleting only with POST | GET shows the question "Delete?", and only the confirmation deletes – a link by itself deletes nothing |
{% extends "base.html" %}
{% load static %}
{% block naslov %}Generator – Logo Creator{% endblock %}
{% block sadrzaj %}
<div class="container py-4">
<h1 class="h3 mb-4">Logo generator</h1>
<div class="row g-4">
<form id="forma" class="col-md-5" method="post">
{% csrf_token %}
{% for field in form %}
<div class="mb-3">
<label for="{{ field.id_for_label }}" class="form-label">{{ field.label }}</label>
{{ field }}
{% for error in field.errors %}<div class="text-danger small">{{ error }}</div>{% endfor %}
</div>
{% endfor %}
{% if user.is_authenticated %}
<button type="submit" class="btn btn-danger">Save to "My logos"</button>
{% else %}
<p class="small text-body-secondary"><a href="{% url 'login' %}?next={{ request.get_full_path|urlencode }}">Sign in</a> to save logos.</p>
{% endif %}
<button type="button" id="preuzmiSvg" class="btn btn-outline-danger">Download SVG</button>
<button type="button" id="preuzmiPng" class="btn btn-outline-danger">Download PNG</button>
</form>
<div class="col-md-7 text-center">
<div id="prikaz" class="p-3 bg-white rounded shadow-sm"></div>
</div>
</div>
</div>
{% endblock %}
{% block skripte %}
<script src="{% static 'logoi/js/generator.js' %}"></script>
{% endblock %}
The JavaScript from the lesson Logo generator stays almost the same:
// logoi/static/logoi/js/generator.js – the change compared with lesson 16 of the HTML/CSS/JS course:
// the fields are now made by the Django form (the ids are the same thanks to auto_id="%s"),
// and the name from the address has already been put into the field on the server (initial), so the part with URLSearchParams is no longer needed.
// The rest of the file (el, initials, draw, downloading) is the same.
{# templates/logoi/_logo_svg.html – draws a saved logo on the server (the same look as generator.js) #}
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 200" width="100%" role="img" aria-label="Logo {{ logo.naziv }}">
{% if logo.oblik == "krug" %}
<circle cx="100" cy="100" r="70" fill="{{ logo.boja }}"/>
{% elif logo.oblik == "kvadrat" %}
<rect x="30" y="30" width="140" height="140" rx="24" fill="{{ logo.boja }}"/>
{% else %}
<polygon points="100,25 175,100 100,175 25,100" fill="{{ logo.boja }}"/>
{% endif %}
<text x="100" y="116" text-anchor="middle" font-size="46" font-weight="bold" font-family="{{ logo.font }}" fill="#fff">{{ logo.inicijali }}</text>
<text x="195" y="{% if logo.slogan %}100{% else %}112{% endif %}" font-size="28" font-weight="bold" font-family="{{ logo.font }}" fill="#222">{{ logo.naziv }}</text>
{% if logo.slogan %}
<text x="197" y="132" font-size="16" font-family="{{ logo.font }}" fill="{{ logo.boja }}">{{ logo.slogan }}</text>
{% endif %}
</svg>
A saved logo is drawn on the server with the same SVG elements as in the generator. Django automatically "escapes" the values from the database ({{ logo.naziv }}), so even a name with <script> cannot do any harm.
{% extends "base.html" %}
{% block naslov %}My logos – Logo Creator{% endblock %}
{% block sadrzaj %}
<div class="container py-4">
<div class="d-flex justify-content-between align-items-center mb-3">
<h1 class="h3 mb-0">My logos ({{ logos|length }})</h1>
<a class="btn btn-danger" href="{% url 'generator' %}">+ New logo</a>
</div>
<div class="row g-3">
{% for logo in logos %}
<div class="col-12 col-md-6 col-lg-4">
<div class="card h-100 shadow-sm">
<div class="card-body">{% include "logoi/_logo_svg.html" %}</div>
<div class="card-footer d-flex justify-content-between align-items-center">
<small class="text-body-secondary">{{ logo.napravljen|date:"d M Y, H:i" }}</small>
<a class="btn btn-sm btn-outline-danger" href="{% url 'obrisi' logo.pk %}">Delete</a>
</div>
</div>
</div>
{% empty %}
<p>You have no saved logos yet. <a href="{% url 'generator' %}">Make the first one!</a></p>
{% endfor %}
</div>
</div>
{% endblock %}
{% extends "base.html" %}
{% block sadrzaj %}
<div class="container py-4" style="max-width: 520px">
<h1 class="h4">Delete the logo "{{ logo.naziv }}"?</h1>
<div class="my-3">{% include "logoi/_logo_svg.html" %}</div>
<form method="post">
{% csrf_token %}
<button class="btn btn-danger">Yes, delete</button>
<a class="btn btn-secondary" href="{% url 'moji_logoi' %}">Cancel</a>
</form>
</div>
{% endblock %}
{% empty %} is shown when the list is empty, and the filter date:"d M Y, H:i" prints the date in a readable form (e.g. 23 Nov 2026, 14:05).
Django has a built-in test system: it runs the project with a temporary, empty database and checks the responses. Tests that guard the most important rules:
# logoi/tests.py
from django.contrib.auth.models import User
from django.test import TestCase
from django.urls import reverse
from .models import Logo
class LogoTests(TestCase):
def setUp(self):
self.ana = User.objects.create_user("ana", password="Password.2026")
self.mark = User.objects.create_user("mark", password="Password.2026")
self.logo = Logo.objects.create(vlasnik=self.ana, naziv="Pupin Club")
def test_initials(self):
self.assertEqual(self.logo.inicijali(), "PC")
def test_saving_sets_the_owner(self):
self.client.login(username="mark", password="Password.2026")
self.client.post(reverse("generator"), {"naziv": "My club", "slogan": "", "boja": "#112233",
"oblik": "krug", "font": "Arial, sans-serif"})
self.assertEqual(Logo.objects.get(naziv="My club").vlasnik, self.mark)
def test_someone_elses_logo_is_not_deleted(self):
self.client.login(username="mark", password="Password.2026")
response = self.client.post(reverse("obrisi", args=[self.logo.pk]))
self.assertEqual(response.status_code, 404)
self.assertTrue(Logo.objects.filter(pk=self.logo.pk).exists())
def test_my_logos_requires_sign_in(self):
response = self.client.get(reverse("moji_logoi"))
self.assertEqual(response.status_code, 302) # redirect to the sign-in page
python manage.py test
Run the tests after every bigger change. If someone accidentally removes the owner check from the view, the test test_someone_elses_logo_is_not_deleted will fail immediately.
Each task has an example, a hint and a solution.
Add the page /moji-logoi/<pk>/edit/ on which a user changes their logo in the generator (the form filled in with the existing values) and an "Edit" button on the card in "My logos".
fields – set it in the view.request.user; a pk in the address alone is no protection.naziv, slogan, boja, oblik, font.1. Why is the owner of a logo set in the view and not chosen in the form?
2. What does get_object_or_404(Logo, pk=5, vlasnik=request.user) return if logo 5 belongs to someone else?
3. What does save(commit=False) do?