From 799ce8d72c7c1dea17302470150e7b66b179f32f Mon Sep 17 00:00:00 2001 From: mipel Date: Fri, 17 Sep 2021 09:16:55 +0200 Subject: [PATCH] #18 File upload in certain folders * removes document file folder if the last CompensationDocument is removed from a compensation --- compensation/models.py | 44 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/compensation/models.py b/compensation/models.py index b4a3de37..51f3ffc7 100644 --- a/compensation/models.py +++ b/compensation/models.py @@ -5,10 +5,12 @@ 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.core.validators import MinValueValidator -from django.db.models import Sum +from django.db.models import Sum, QuerySet from django.utils.translation import gettext_lazy as _ from codelist.models import KonovaCode @@ -197,6 +199,17 @@ class Compensation(AbstractCompensation): y, ) + def get_documents(self) -> QuerySet: + """ Getter for all documents of a compensation + + Returns: + docs (QuerySet): The queryset of all documents + """ + docs = CompensationDocument.objects.filter( + instance=self + ) + return docs + class CompensationDocument(AbstractDocument): """ @@ -212,6 +225,35 @@ class CompensationDocument(AbstractDocument): max_length=1000, ) + def delete(self, *args, **kwargs): + """ + Custom delete functionality for CompensationDocuments. + Removes the folder from the file system if there are no further documents for this entry. + + Args: + *args (): + **kwargs (): + + Returns: + + """ + comp_docs = self.instance.get_documents() + + folder_path = None + if comp_docs.count() == 1: + # The only file left for this compensation is the one which is currently processed and will be deleted + # Make sure that the compensation 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) + class EcoAccount(AbstractCompensation): """