以编程方式将图像保存到 Django ImageField 在生产中返回 404

Programmatically saving image to Django ImageField returning 404 in production

我有一个 Django 应用程序,用户可以在其中上传图像,并且可以根据需要获得图像的处理版本。处理函数 return 是路径,所以我的方法是

model2.processed_image = processingfunction( model1.uploaded_image.path)

作为处理函数 return 的路径在我的管理视图中是这样的

不像正常上传的图片

在我的机器上它工作正常,当我尝试从

更改已处理的 url 时,我总是收到已处理的 404 错误,而正常上传的正确显示
myurl.com/media/home/ubuntu/Eyelizer/media/path/to/the/image 
 to 
myurl.com/media/path/to/the/image

那我该如何解决呢?有没有更好的方法将图像手动保存到数据库?

我有相同的功能,但 return 是一个 Pil.image.image 对象,我尝试了很多方法将其保存在模型中,但我不知道如何实现该功能return 文件路径。

我认为问题出在我定义媒体路径的 nginx 上。

should/can 我重写了processedimage的url属性? 制作类似

的东西
model.processed_image.url = media/somefolder/filename

创建一个 django.core.files.File,而不是直接使用 PIL Image。

示例:

from io import BytesIO
from django.core.files import File

img_io = BytesIO() # create a BytesIO object to temporarily save the file in memory
img = processingfunction( model1.uploaded_image.path)
img.save(img_io, 'PNG') # save the PIL image to the BytesIO object

img_file = File(thumb_io, name='some-name.png') # create the File object
# you can use the `name` from `model1.uploaded_image` and use 
# that above

# finally, pass the image file to your model field
model2.processed_image = img_file

为避免重复此代码,最好将此代码直接保存在 processingfunction 和 return File 对象中。

我的方法与@Xyres 的有点不同,我认为 xyres 会复制现有图像并创建一个新图像,当我尝试覆盖 URL 属性时,它返回了

can't set the attribute

但是当我看到 this question and this 票时,我试着做了这个并且成功了

model2.processed_image = processingfunction(model1.uploaded_image.path)
full_path = model2.processed_image.path
model2.processed_image.name = full_path.split('media')[1]

以便明确制作 URL media/path/to/image 并删除所有不需要的部分,如 home/ubuntu 和东西