Remove previous image from media folder when ImageFiled entry modified in Django

笑着哭i 提交于 2020-07-11 05:37:31

问题


I have a Model with a ImageField.

class Photo(models.Model):
  ----
  image = models.ImageField(verbose_name=_('Image'),upload_to='images/category/%Y/%m/%d/',
            max_length=200,null=True,blank=True)
  ---

I edited this model and changed the image field by uploading a new image.

My question, Is there a way to delete the previous image from its directory(from media folder) when I updates this entry with new image. I am using django 1.4.3 .


回答1:


You can either use django's signals or simply overwrite the save method on your model. I would write a signal. Something like the following (note that this is untested):

from django.db.models.signals import pre_save
from django.dispatch import receiver

class Photo(models.Model):
     image = ...

@receiver(pre_save, sender=Photo)
def delete_old_image(sender, instance, *args, **kwargs):
    if instance.pk:
        existing_image = Photo.objects.get(pk=instance.pk)
        if instance.image and existing_image.image != instance.image:
            existing_image.image.delete(False)


来源:https://stackoverflow.com/questions/19287719/remove-previous-image-from-media-folder-when-imagefiled-entry-modified-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!