使用S3BotoStorag移动文件

2024-09-28 05:42:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用来自django-storagesS3BotoStorage来处理Django后端的S3存储桶上的媒体和静态文件。在

一切都如预期的那样工作,但是后端会引发一个notimplementedError,因为当我调用时它不是本地文件系统self.image.path在图像是模特。形象字段。这是expected behavior。在

但是我用路径来移动图像操作系统重命名(这对我的水桶也没用)。将文件移动到存储桶上的方法是什么?在


Tags: 文件pathdjango图像imageselfs3静态
1条回答
网友
1楼 · 发布于 2024-09-28 05:42:08

不应该使用os来移动文件,而应该使用storage

要移动文件,可以在FileField(或者在本例中是ImageField)上使用read()方法(最后使用storage删除旧文件)。

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)

相关问题 更多 >

    热门问题