49 lines
1.4 KiB
Python
49 lines
1.4 KiB
Python
import os
|
|
import shutil
|
|
import uuid
|
|
|
|
from django.db import models
|
|
from django.dispatch import receiver
|
|
|
|
from .models import Exercice
|
|
from api.settings import MEDIA_ROOT
|
|
|
|
|
|
# These two auto-delete files from filesystem when they are unneeded:
|
|
|
|
@receiver(models.signals.post_delete, sender=Exercice)
|
|
def auto_delete_file_on_delete(sender, instance, **kwargs):
|
|
"""
|
|
Deletes file from filesystem
|
|
when corresponding `MediaFile` object is deleted.
|
|
"""
|
|
|
|
if instance.exo_model:
|
|
if os.path.isfile(instance.exo_model.path):
|
|
os.remove(instance.exo_model.path)
|
|
if os.path.isdir(f'{MEDIA_ROOT}/uploads/exercices/exo_{instance.id_code}'):
|
|
shutil.rmtree(f'{MEDIA_ROOT}/uploads/exercices/exo_{instance.id_code}')
|
|
#os.rmdir(f'{MEDIA_ROOT}/uploads/exercices/exo_{instance.id_code}')
|
|
|
|
|
|
|
|
@receiver(models.signals.pre_save, sender=Exercice)
|
|
def auto_delete_file_on_change(sender, instance, **kwargs):
|
|
"""
|
|
Deletes old file from filesystem
|
|
when corresponding `MediaFile` object is updated
|
|
with new file.
|
|
"""
|
|
if not instance.pk:
|
|
return False
|
|
|
|
try:
|
|
old_file = Exercice.objects.get(id_code=instance.id_code).exo_model
|
|
except Exercice.DoesNotExist:
|
|
return False
|
|
|
|
new_file = instance.exo_model
|
|
if not old_file == new_file:
|
|
if os.path.isfile(old_file.path):
|
|
os.remove(old_file.path)
|
|
|