【问题标题】:set default image on model from s3 bucket从 s3 存储桶在模型上设置默认图像
【发布时间】:2022-01-18 18:38:47
【问题描述】:

对于用户配置文件,我在模型上有一个默认图像

image = models.ImageField(default='default.jpg', upload_to='profile_pics')

我现在在 s3 存储桶中有这张图片。如何从 s3 存储桶而不是本地引用此图像

如果我尝试使用模型上的直接图像路径 https://uploadfiles.s3.amazonaws.com/profile_pics/default.jpg 或存储桶路径 'uploadfiles/profile_pics/default.jpg 我收到错误 This backend doesn't support absolute paths

我不确定如何引用我确实可以正确访问存储桶并且上传工作正常的图像

更新:

我更正了 This backend doesn't support absolute paths 违规代码是 img = Image.open(self.image.path) 我更正了 img = Image.open(self.image.name) 仍然很难将文件放在应用程序满意的位置

更新 2:

因此,在我的静态文件夹中,我创建了一个名为 staticimages 的文件夹,默认图像为 static\staticimages\default.jpg,然后运行 ​​collectstatic 并将文件上传到 s3 存储桶。现在的问题是,当文件上传到 s3 时,它们不在名为 static 的文件夹中,文件直接上传到存储桶。因此,模型上文件的链接不再有效,因为 s3 存储桶上不存在 static 文件夹,但它在本地存在,这会导致文件不存在的错误。如果目录结构永远无法从本地匹配到 s3,那么如何链接文件。

更新3:

如果我将图像放在 s3 存储桶的根目录中,它就可以工作。虽然这并不理想,但我宁愿将它放在一个文件夹中,这暂时可以使用

【问题讨论】:

    标签: django amazon-s3 django-models


    【解决方案1】:

    尝试这样的方法来为图像构建绝对 uri,剩下的就是 S3 上的存储桶策略。

    from django.contrib.sites.models import Site
    from urllib.parse import urljoin
    from django.utils.encoding import iri_to_uri
    
    def build_absolute_uri(location):
        # type: (str) -> str
        host = Site.objects.get_current().domain
        protocol = "https" if settings.ENABLE_SSL else "http"
        current_uri = "%s://%s" % (protocol, host)
        location = urljoin(current_uri, location)
        return iri_to_uri(location)
    
    
    @celery_app.task()
    def send_expense_record(id):
        send_kwargs, ctx = get_email_context()
        expense = Expense.objects.get(pk=id)
        imagelink = build_absolute_uri(expense.image.url)
        ctx["imagelink"] = imagelink
        email = send_templated_mail(
         template_name="property/expense",
         recipient_list=settings.ADMINS,
         context=ctx,
            **send_kwargs,
        )
    
        return email
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 2015-03-12
      • 2013-10-30
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多