Django将ImageField指向一个已经存在的图像 [英] Django point ImageField to an already existing image

查看:39
本文介绍了Django将ImageField指向一个已经存在的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有图像"字段的模型:

I have a model which has an Image field:

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

我正在使用urllib通过Internet下载图像,如下所示:

I am downloading an image over the internet using urllib like this:

urllib.urlretrieve(img_url, img_path)

现在,我想将图像"字段指向该另存为img_path的下载图像.我试过使用 PIL 中的 Image.open()首先打开文件并指向它,然后指向 obj.image.save(File(open(file_path)))使用 django.core.files.File ,但它们似乎不起作用.有替代的方法可以实现吗?

Now I want to point the Image field to this downloaded image saved as img_path. I have tried using Image.open() from PIL to first open the file and point to it and obj.image.save(File(open(file_path))) using django.core.files.File but they don't seem to work. Is there an alternate way to implement this?

推荐答案

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

You can simple set the image field to the new path and save the object:

obj.image = img_path
obj.save()

请注意, img_path 必须相对于您的 MEDIA_ROOT 设置.

这篇关于Django将ImageField指向一个已经存在的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆