【问题标题】:How do I delete the previous saved image and save the new one without duplicating? Django如何删除之前保存的图像并保存新图像而不重复?姜戈
【发布时间】:2018-12-27 05:27:38
【问题描述】:

我无法保存图片。我的模型是这个

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

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

如果用户上传图片,它会删除用户之前的图片 它会以唯一的名称保存新图像。

我该怎么做?

【问题讨论】:

    标签: django image profile django-2.0 imagefield


    【解决方案1】:

    使用信号试试这个

    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)
    

    【讨论】:

      猜你喜欢
      • 2016-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      • 2018-03-26
      • 2012-08-19
      • 1970-01-01
      相关资源
      最近更新 更多