如何删除以前保存的图像并保存新图像而不复制?姜戈



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

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)

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

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

当我使用此模型保存图像时,它与自动唯一名称一起保存。见下图,

文件系统截图

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

如果用户上传了图片,则会删除该用户的上一张图片 它将使用唯一名称保存新图像。

我该怎么做?

使用信号尝试此操作

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)

最新更新