from django.core.files.storage import get_storage_class
default_storage = get_storage_class()()
@receiver(pre_delete, sender=OrganizationFile)
def delete_has_folder(sender, instance, *args, **kwargs):
# get filename that will be equals to the relative path but not actually the filename
path = Path(instance.file.name)
# get a parent folder str
folder_path = str(path.parent)
# delete a file
instance.file.delete()
# delete a folder.
# shutil.rmtree(absolute_path) wouldn't work
# because instance.file.path will raise an error.
# hence the only way is to delete with a storage default_storage.delete
default_storage.delete(folder_path)
logger.info(f'Pre delete {instance}. Deleted the hash folder {folder_path}')