如何删除以前保存的图像并在不复制的情况下保存新图像?姜戈

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

我在保存图像时遇到问题。我的模特是这个

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)

此模型具有与默认用户模型和图像字段的 OneToOne 关系字段。

我正在覆盖 save() 方法来重新调整图像的大小。

但是

当我用这个模型保存图像时,它被自动保存为唯一的名称。见下图,

Screenshot of file system

但是我想这样保存图片..

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.

我该怎么做?

使用信号试试这个

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)