Upload to FileField/ImageField with unique names

Today, 25th June 2022, Ukraine is still bravely fighting for democratic values, human rights and peace in whole world. Russians ruthlessly kill all civilians in Ukraine including childs and destroy their cities. We are uniting against Putinโ€™s invasion and violence, in support of the people in Ukraine. You can help by donating to Ukrainian's army.

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:

  1. Create utils.py file in project root
  2. Add next class there:

from django.utils.deconstruct import deconstructible
import shortuuid
import os

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)
Ivan Borshchov profile picture
Jun 20, 2020
by Ivan Borshchov
Did it help you?
Yes !

Best related