Delete photo when not referenced any more by Recette instance
This commit is contained in:
parent
45de848cbe
commit
4f48503ab1
|
@ -1,4 +1,6 @@
|
|||
import os
|
||||
from django.db import models
|
||||
from django.dispatch import receiver
|
||||
from django.urls import reverse
|
||||
|
||||
from .fields import ChoiceArrayField
|
||||
|
@ -52,3 +54,35 @@ class Composition(models.Model):
|
|||
|
||||
def __str__(self):
|
||||
return "%s %s %s" % (self.quantite, self.unite.nom, self.ingredient.nom)
|
||||
|
||||
|
||||
@receiver(models.signals.post_delete, sender=Recette)
|
||||
def auto_delete_photo_on_delete(sender, instance, **kwargs):
|
||||
"""
|
||||
Delete file from filesystem
|
||||
when corresponding `Recette` object is deleted.
|
||||
"""
|
||||
if instance.photo:
|
||||
if os.path.isfile(instance.photo.path):
|
||||
os.remove(instance.photo.path)
|
||||
|
||||
|
||||
@receiver(models.signals.pre_save, sender=Recette)
|
||||
def auto_delete_photo_on_change(sender, instance, **kwargs):
|
||||
"""
|
||||
Delete old file from filesystem
|
||||
when corresponding `Recette` object is updated
|
||||
with new file.
|
||||
"""
|
||||
if not instance.pk:
|
||||
return False
|
||||
|
||||
try:
|
||||
old_file = Recette.objects.get(pk=instance.pk).photo
|
||||
except Recette.DoesNotExist:
|
||||
return False
|
||||
|
||||
new_file = instance.photo
|
||||
if not old_file == new_file:
|
||||
if os.path.isfile(old_file.path):
|
||||
os.remove(old_file.path)
|
||||
|
|
Loading…
Reference in a new issue