#18 File upload in certain folders

* removes document file folder if the last EmaDocument is removed from an Ema
This commit is contained in:
mipel 2021-09-17 09:24:31 +02:00
parent e7b6b4dd8d
commit 1edc1edc98

View File

@ -1,5 +1,8 @@
import shutil
from django.contrib.auth.models import User
from django.db import models
from django.db.models import QuerySet
from compensation.models import AbstractCompensation
from konova.models import AbstractDocument, generate_document_file_upload_path
@ -86,6 +89,17 @@ class Ema(AbstractCompensation):
return ret_msgs
def get_documents(self) -> QuerySet:
""" Getter for all documents of an EMA
Returns:
docs (QuerySet): The queryset of all documents
"""
docs = EmaDocument.objects.filter(
instance=self
)
return docs
class EmaDocument(AbstractDocument):
"""
@ -100,3 +114,32 @@ class EmaDocument(AbstractDocument):
upload_to=generate_document_file_upload_path,
max_length=1000,
)
def delete(self, *args, **kwargs):
"""
Custom delete functionality for EcoAccountDocuments.
Removes the folder from the file system if there are no further documents for this entry.
Args:
*args ():
**kwargs ():
Returns:
"""
ema_docs = self.instance.get_documents()
folder_path = None
if ema_docs.count() == 1:
# The only file left for this EMA 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)