diff --git a/intervention/models.py b/intervention/models.py index 31b430f..fb344b2 100644 --- a/intervention/models.py +++ b/intervention/models.py @@ -5,6 +5,8 @@ Contact: michel.peltriaux@sgdnord.rlp.de Created on: 17.11.20 """ +import shutil + from django.contrib.auth.models import User from django.contrib.gis.db import models from django.utils.timezone import localtime @@ -338,3 +340,38 @@ class InterventionDocument(AbstractDocument): upload_to=generate_document_file_upload_path, max_length=1000, ) + + def delete(self, *args, **kwargs): + """ + Custom delete functionality for InterventionDocuments. + Removes the folder from the file system if there are no further documents for this entry. + + Args: + *args (): + **kwargs (): + + Returns: + + """ + revoc_docs = RevocationDocument.objects.filter( + instance=self.instance.legal.revocation + ) + other_intervention_docs = InterventionDocument.objects.filter( + instance=self.instance + ) + + folder_path = None + if revoc_docs.count() == 0 and other_intervention_docs.count() == 1: + # The only file left for this intervention is the one which is currently processed and will be deleted + # Make sure that the intervention folder itself is deleted as well, not only the file + # Therefore take the folder path from the file path + folder_path = self.file.path.split("/")[:-1] + folder_path = "/".join(folder_path) + + # Remove the file itself + super().delete(*args, **kwargs) + + # If a folder path has been set, we need to delete the whole folder! + if folder_path is not None: + shutil.rmtree(folder_path) +