Django storages S3 - Store existing file
Asked Answered
M

1

5

I have django 1.11 with latest django-storages, setup with S3 backend.

I am trying to programatically instantiate an ImageFile, using the AWS image link as a starting point. I cannot figure out how to do this looking at the source / documentation.

I assume I need to create a file, and give it the path derived from the url without the domain, but I can't find exactly how.

The final aim of this is to programatically create wagtail Image objects, that point to S3 images (So pass the new ImageFile to the Imagefield of the image). I own the S3 bucket the images are stored in it.

Uploading images works correctly, so the system is setup correctly.

Update

To clarify, I need to do the reverse of the normal process. Normally a physical image is given to the system, which then creates a ImageFile, the file is then uploaded to S3, and a URL is assigned to the File.url. I have the File.url and need an ImageFile object.

Milium answered 30/5, 2018 at 16:38 Comment(0)
M
12

It turns out, in several models that expect files, when using DjangoStorages, all I had to do is instead of passing a File on the file field, pass the AWS S3 object key (so not a URL, just the object key). When model.save() is called, a boto call is made to S3 to verify an object with the provided key is there, and the item is saved.

Milium answered 11/6, 2018 at 19:34 Comment(2)
For clarification this means: my_model.upload = "s3 object key.jpg" instead of my_model.upload.save(...)Metallurgy
I'm attempting to do the exact same thing, but I'm getting an error. djfile = Media.objects.create(asset_title='Title 1", image_file=my_bucket_object) generates an AttributeError: 's3.ObjectSummary' object has no attribute '_committed'Pipestone

© 2022 - 2025 — McMap. All rights reserved.