快速问题:如何将文件与Django中的ImageField相关联?

2024-04-26 14:30:34 发布

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

我的硬盘上保存了一张图片,我想把它分配给一个ImageField,但我不知道怎么做。在

我试过这样的方法: object.imagefield.save(path,File(open(path)))

但这会生成一个额外的(无效的)图像副本。在

有人能帮帮我吗?在

谢谢!在


Tags: path方法图像objectsave副本图片open
2条回答

也许有更好的方法,但我会做一些类似的事情:

from django.core.files.base import ContentFile

srcFile = ContentFile( srcData ) # srcData is the contents of the local file
srcFile.open()
myObject.image.save(name=filename, content=srcFile)

我通常只需为图像字段指定一个带有图像路径的字符串,如下所示:

MyObject.image="/photo_path/photo_name.jpg"
MyObject.save()

我不知道这样做是否有错,但它总是有效的。在

相关问题 更多 >