Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django point ImageField to an already existing image

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?

like image 512
Keshav Agarwal Avatar asked Oct 18 '25 13:10

Keshav Agarwal


1 Answers

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.

like image 71
ilse2005 Avatar answered Oct 21 '25 02:10

ilse2005



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!