问题
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