From ab631aeb902a12a2a4c987d5a01be0ad1c7ef221 Mon Sep 17 00:00:00 2001 From: Dariusz Niemczyk Date: Sun, 14 Jan 2024 21:47:19 +0100 Subject: [PATCH] feat: make media uploaded files generate uuid name --- storage/models.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/storage/models.py b/storage/models.py index e857770..55b741b 100644 --- a/storage/models.py +++ b/storage/models.py @@ -1,4 +1,5 @@ from __future__ import unicode_literals +import os import uuid import re @@ -129,9 +130,16 @@ class Item(models.Model, TreeModelMixin): ordering = ("path",) +class ImageFieldWithUuid(models.ImageField): + def generate_filename(self, instance, filename): + ext = filename.split(".")[-1] + filename = "%s.%s" % (uuid.uuid4(), ext) + return super().generate_filename(instance, filename) + + class ItemImage(models.Model): item = models.ForeignKey(Item, related_name="images", on_delete=models.CASCADE) - image = models.ImageField() + image = ImageFieldWithUuid() def __str__(self): return "{}".format(self.image.name)