Yorbjörn
Yorbjörn

Reputation: 456

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

@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:

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)

Upvotes: 0

Views: 1217

Answers (1)

sitWolf
sitWolf

Reputation: 1011

django-storages has an optional setting AWS_S3_FILE_OVERWRITE. By default, it is set to True (reference). That is, by default files with the same name will overwrite each other. Set this to False to have extra characters appended.

Upvotes: 1

Related Questions