Upload to FileField/ImageField with unique names
Any time you upload a new file in Django's FileField/ImageField with the old name you might face with Browser/CDN caching issue.
To solve it we suggest adding some unique token in a filename in the upload function.
To implement it:
- Create
utils.py
file in project root - Add next class there:
from django.utils.deconstruct import deconstructible
import shortuuid
import os
@deconstructible
class HashedUploadTo(object):
def __init__(self, path):
self.path = path
def __call__(self, instance, filename):
filename_base, filename_ext = os.path.splitext(filename)
return f"{self.path}{filename_base}.{shortuuid.uuid()}{filename_ext}"
Now to use it:
import utils
logo = models.ImageField(upload_to=utils.HashedUploadTo('myLogos/'), default=None, blank=True)