Tuesday, 22 September 2020

Django ImageField: directly using file from disk

I have a file on my disk, say:

/home/user/file.png

And I have a model with a StdImageField (which is similar to the ImageField, just some additional options), more here.

models.py:

class MyModel(models.Model):
    image = StdImageField(upload_to="images", variations={"thumbnail": (600,400), "normal": (1000, 600)}, blank=True, null=True)

What I'd like to do is programatically "upload" this image. I do not just want to assign the existing path to the field, as I want the image to be stored in the right folder and properly resized.

So let's say I have an instance of my model in the variable obj, then I'm trying to do the following:

from django.core.files.images import ImageFile
open_file = open("/home/user/file.png", "rb")
django_file = ImageFile(open_file)
obj.image = django_file
obj.save()

Now at first sight this works well because a) my image gets moved to the right folder images in my media root, and b) the image gets resized properly. However, after this operation the database field with the path to the file turns absolute, containing the entire path to the media root:

/src/media/images/file.png

But this is not how it normally works -- this is supposed to be relative and only contain:

images/file.png

Why does it become an absolute field and how to solve this?



from Django ImageField: directly using file from disk

No comments:

Post a Comment