Django将ImageField指向已存在的图像

时间:2016-03-04 10:45:35

标签: python django python-2.7 django-models

我的模型有一个Image字段:

class Foo(models.Model):
    image = models.ImageField(upload_to = "bar", blank = True)

我正在使用urllib在互联网上下载图像:

urllib.urlretrieve(img_url, img_path)

现在我想将Image字段指向保存为img_path的下载图像。我尝试使用Image.open()中的PIL来首先打开文件并使用obj.image.save(File(open(file_path)))指向它并django.core.files.File但它们似乎无法正常工作。有没有其他方法可以实现这个?

3 个答案:

答案 0 :(得分:3)

您可以简单地将image字段设置为新路径并保存对象:

obj.image = img_path
obj.save()

编辑:

请注意,img_path必须与您的MEDIA_ROOT设置相关。

答案 1 :(得分:1)

ImageFieldFile.save将文件名作为第一个参数。

试试这个:

from PIL import Image
im = Image.open(file_path)
save_file_path = get_the_image_upload_to(obj)
obj.image.save(save_file_path, im)

不确定im是否足够,或者您是否应该执行以下操作:

from io import BytesIO

from PIL import Image

im = Image.open(file_path)
save_file_path = get_the_image_upload_to(obj)
file_io = BytesIO()
im.save(file_io)
file_io.seek(0)
obj.image.save(save_file_path, file_io.read())

答案 2 :(得分:0)

稍微修补ilse2005's回答。我发现直接设置路径是有效的。路径必须相对于您的媒体根,它就像一个魅力。

所以通过这个定义,这段代码非常完美:

obj.image = os.path.join('bar', img_name)
obj.save()