简体   繁体   English

在上传具有相同名称的新图像之前删除 S3 存储桶上的图像

[英]Delete Image on S3 bucket before uploading new image with the same name

I have a model, that on save, it uploads my image to my S3 bucket.我有一个 model,它在保存时会将我的图像上传到我的 S3 存储桶。 But I'm having some trouble when I want to reupload an image with the same name.但是当我想重新上传具有相同名称的图像时遇到了一些麻烦。 (Example: when a logo updates it needs to be reuploaded) (例如:徽标更新时需要重新上传)

Because the image already exists, Django extends the pathname with it's own generated extention to make it unique.由于图像已经存在,Django 使用它自己生成的扩展名扩展路径名以使其唯一。 We don't want that, we want to delete the existing image before uploading the new image.我们不希望这样,我们想在上传新图像之前删除现有图像。 That way, the extention is no more.这样,扩展就不再存在了。

I've tried removing my image first with the pre_save signal, but that just makes my imagefield empty我试过先用 pre_save 信号删除我的图像,但这只会让我的图像字段为空

@receiver(pre_save, sender=geo_models.Logo)
def remove_file_from_s3(sender, instance, using, **kwargs):
    instance.png.delete(save=False)

Any way of doing this?有什么办法吗?

Model: Model:

class Logo(models.Model):
    logo_type_choices = Choices(
        ('ENTITY', _('Entity')),
        ('BRAND', _('Brand')),
    )

    class Meta:
        verbose_name = _('logo')
        verbose_name_plural = _('logos')

    png = models.ImageField(
        verbose_name='{0} {1}'.format('png', _('image')),
        upload_to=get_upload_loc_png,
        validators=[validators.validate_png_extension],
        storage=storage,
        max_length=200,
        blank=True,
        null=True,
    )

    logo_type = models.CharField(choices=logo_type_choices, max_length=20)

django-storages has an optional setting AWS_S3_FILE_OVERWRITE . django-storages 有一个可选设置AWS_S3_FILE_OVERWRITE By default, it is set to True ( reference ).默认情况下,它设置为 True ( 参考)。 That is, by default files with the same name will overwrite each other.也就是说,默认情况下,具有相同名称的文件将相互覆盖。 Set this to False to have extra characters appended.将此设置为 False 以附加额外的字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM