From c70372780e0a2fa89548d739c66b4376fb2c9f76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bodor=20M=C3=A1t=C3=A9?= <bodor.mate@kszk.bme.hu> Date: Sat, 16 Feb 2019 13:09:06 +0100 Subject: [PATCH] Delet file when model deleted and set file save path --- src/document/models.py | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/document/models.py b/src/document/models.py index a9d72a2..8e26ea2 100644 --- a/src/document/models.py +++ b/src/document/models.py @@ -1,11 +1,22 @@ +import os + from django.db import models from django.core import validators - +from django.dispatch import receiver from account.models import Profile from homework.models import Solution from common.validators import FileSizeValidator +def document_file_name(instance, filename): + return '/'.join([ + 'document', + instance.solution.task.title, + instance.uploaded_by.full_name, + filename + ]) + + class Document(models.Model): uploaded_by = models.ForeignKey(Profile, on_delete=models.DO_NOTHING) uploaded_at = models.DateTimeField(auto_now_add=True, editable=False) @@ -22,9 +33,18 @@ class Document(models.Model): FileSizeValidator(size_limit=52428800), # 52428800 - 50MiB ], blank=True, - null=True + null=True, + upload_to=document_file_name ) solution = models.ForeignKey(Solution, related_name='files', on_delete=models.CASCADE) def __str__(self): return self.name + + +# Deletes file from filesystem when File object is deleted. +@receiver(models.signals.post_delete, sender=Document) +def auto_delete_file_on_delete(sender, instance, **kwargs): + if instance.file: + if os.path.isfile(instance.file.path): + os.remove(instance.file.path) -- GitLab