Django - generate a unique suffix to an uploaded file (uuid is cut and django adds another suffix)

201 Views Asked by At

I'm going to use DigitalOcean Spaces as a file storage and I want to add suffixes to uploaded filenames for two reasons:

  • impossible to guess file url with bruteforce
  • ensure it is unique, as I'm not sure if Django can check for filename uniqueness on S3

This is the method:

def cloudfile_upload_to(instance, filename):
    path = storage_path_service.StoragePathService.cloud_dir(instance.cloud)
    filename, ext = os.path.splitext(filename)
    _uuid = uuid.uuid4()
    return os.path.join(path, f"{filename}-{uuid}{ext}")

in the code:

path == "user/11449_bacccbe4-6794-42e3-89c3-5045b024fa11/income/1541/cloud"
filename, ext = "webp", ".webp"
uuid == "f8851579-3aa6-403b-bc08-86923d72e80b"

When I check the file it is in a correct dir, but the filename is:

"webp-527846f0-4284-4e_YvqcSrf.webp"

AS you can see, uuid is cut and Django adds it's own suffix. How to make it work?

0

There are 0 best solutions below