Django point ImageField to an already existing image

梦想与她 提交于 2021-02-09 09:22:06

问题


I have a model which has an Image field:

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

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

urllib.urlretrieve(img_url, img_path)

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?


回答1:


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

obj.image = img_path
obj.save()

Edit:

Note that img_path has to be relative to your MEDIA_ROOT setting.




回答2:


ImageFieldFile.save takes the filename as first argument.

Try this out:

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)

Not sure if im is sufficient or if you should do something like:

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())



回答3:


With a little tinkering with ilse2005's answer. I found that setting the path directly works. The path must be relative to your media root, and it works like a charm.

So by that definition, this code works absolutely perfectly:

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


来源:https://stackoverflow.com/questions/35794022/django-point-imagefield-to-an-already-existing-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!