上传新头像时如何删除旧头像 - Django

How to delete old profile picture when upload a new one - Django

我的模型中有一个基于 ImageField 的带有个人资料图片的用户个人资料页面。当我提交表单并上传新图片时,原始图片文件并未从 /static/images/ 中删除。 上传新照片后,如何从图像文件夹中删除旧个人资料照片?

您可以使用pre_save signal在保存新文件之前删除旧文件

from django.db.models.signals import pre_save
import os

@receiver(pre_save, sender=ImageModel)
def delete_old_file(sender, instance, **kwargs):
    # on creation, signal callback won't be triggered 
    if instance._state.adding and not istance.pk:
        return False
    
    try:
        old_file = sender.objects.get(pk=instance.pk).file
    except sender.DoesNotExist:
        return False
    
    # comparing the new file with the old one
    file = instance.file
    if not old_file == file:
        if os.path.isfile(old_file.path):
            os.remove(old_file.path)