【问题标题】:How to programmatically store S3 images in Django如何以编程方式在 Django 中存储 S3 图像
【发布时间】:2020-09-12 06:43:24
【问题描述】:

正如在此处链接的上一个问题中所述,我正在执行将上传到 S3 的 Django 中的图像保存的相反操作。图像已经存在于 S3 中,我想通过创建媒体对象以编程方式将图像添加到 Django。

Django storages S3 - Store existing file

我的班级是这样的:

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 )

在我看来,我有这个:

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)

我目前收到 AttributeError: 's3.ObjectSummary' 对象没有属性 '_committed'

【问题讨论】:

    标签: django amazon-s3 boto3 python-django-storages


    【解决方案1】:

    s3.ObjectSummary 对象可能不会被 Django 识别为图像对象。

    试试这个

    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))  
    

    ContentFile 类继承自 File,但与 File 不同,它操作 字符串内容(也支持字节),而不是实际文件
    documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-21
      • 2018-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多