Search code examples
djangoimageprofiledjango-2.0imagefield

How do I delete the previous saved image and save the new one without duplicating? Django


I'm having trouble saving image. My Model is this

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pic')

def __str__(self):
    return f'{self.user.username} Profile'

def save(self, **kwargs):
    super().save()

    img = Image.open(self.image.path)

    if img.height > 300 or img.width > 300:
        output_size = (300, 300)
        img.thumbnail(output_size)
        img.save(self.image.path)

This model has and OneToOne relation field with the default user model and an image field.

I am overriding the save() method to rezize the image.

But

When I'm saving image with this model, It's saved with and automatic unique name. See the image below,

Screenshot of file system

But I want to save image like this..

If user uploads an image, it'll delete the previous image of the user and it'll save the new image with an unique name.

How do I do it?


Solution

  • Try this using signals

    from django.db.models.signals import post_init, post_save
    from django.dispatch import receiver
    
    from myapp.models import Profile
    
    
    @receiver(post_init, sender= Profile)
    def backup_image_path(sender, instance, **kwargs):
        instance._current_imagen_file = instance.image
    
    
    @receiver(post_save, sender= Profile)
    def delete_old_image(sender, instance, **kwargs):
        if hasattr(instance, '_current_image_file'):
            if instance._current_image_file != instance.image.path:
                instance._current_image_file.delete(save=False)