简体   繁体   中英

Move Files with S3BotoStorage

I'm using S3BotoStorage from django-storages to handle my media and static files on my S3 Bucket for my Django backend.

Everything works as expected, but the backend raises a not ImplementedError because it is not a local filesystem when I call self.image.path on a where Image is a models.Image Field. This is expected behavior .

However I'm using the path to move the image with os.rename (which wouldnt work on my bucket as well). What would be the approach to move that file on the bucket?

Instead of using os to move your file, you should use the storage

To move your file, you can use the read() method on your FileField (or in this case, ImageField ), (and eventually use the storage to delete the old file).

file_content = my_model.my_image.read()
file_name = my_model.my_image.name

# Renaming the file
my_model.my_image = my_model.my_image.save('new_file_name', ContentFile(file_content))

# If you want to delete the original file afterwards:
from django.core.files.storage import default_storage
default_storage.delete(file_name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM