wmfox3
wmfox3

Reputation: 2221

How to programmatically store S3 images in Django

As noted in this previous question linked here, I am doing the reverse of saving images in Django that get uploaded to S3. The images already reside in S3 and I want to programmatically add the images to Django by creating media objects.

Django storages S3 - Store existing file

My class looks like this:

class Media( models.Model ):
    asset_title = models.CharField( 'Title', max_length=255, help_text='The title of this asset.' )
    image_file = models.ImageField( upload_to='upload/%Y/%m/%d/', blank=True )

In my view, I have this:

bucket = s3.Bucket('my-bucket')

for my_bucket_object in bucket.objects.filter(Prefix='media/upload/2020'):
    djfile = Media.objects.create(asset_title=my_bucket_object.key, image_file=my_bucket_object)

I'm currently getting an AttributeError: 's3.ObjectSummary' object has no attribute '_committed'

Upvotes: 3

Views: 800

Answers (1)

Sumithran
Sumithran

Reputation: 6555

s3.ObjectSummary object may not be identified as an image object by Django.

Give this a try

from django.core.files.base import ContentFile

bucket = s3.Bucket('my-bucket')

for my_bucket_object in bucket.objects.filter(Prefix='media/upload/2020'):
    djfile = Media.objects.create(asset_title=my_bucket_object.key, image_file=ContentFile(my_bucket_object))  

The ContentFile class inherits from File, but unlike File, it operates on string content (bytes also supported), rather than an actual file
documentation

Upvotes: 2

Related Questions