Upload to FileField/ImageField with unique names

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:

  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

Other by Ivan Borshchov