diff --git a/scipost_django/finances/forms.py b/scipost_django/finances/forms.py index bd654ea38dde8044a7dfc0541e274f47eeec3bd4..238f78975e1d43fdf917f0169c96aa6a30da477a 100644 --- a/scipost_django/finances/forms.py +++ b/scipost_django/finances/forms.py @@ -263,6 +263,11 @@ class SubsidyAttachmentForm(forms.ModelForm): def clean_attachment(self): attachment = self.cleaned_data["attachment"] + + # Allow already uploaded attachments + if hasattr(self.instance, "attachment") and not attachment is None: + return attachment + filename_regex = ( "^SciPost_" "[0-9]{4,}(-[0-9]{4,})?_[A-Z]{2,}_[\w]+_" diff --git a/scipost_django/finances/models.py b/scipost_django/finances/models.py index e24ca10394d00233cb2d809a1e628abf5bb9093a..a90ba3e00b7380def73d8204aa8ccb4b0bc43e27 100644 --- a/scipost_django/finances/models.py +++ b/scipost_django/finances/models.py @@ -10,6 +10,8 @@ from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.db import models from django.db.models import Sum +from django.db.models.signals import pre_save +from django.dispatch import receiver from django.urls import reverse from django.utils import timezone from django.utils.html import format_html @@ -280,6 +282,17 @@ class SubsidyAttachment(models.Model): return False +# Delete attachment files with same name if they exist, allowing replacement without name change +@receiver(pre_save, sender=SubsidyAttachment) +def delete_old_attachment_file(sender, instance, **kwargs): + if instance.pk: + old_attachment = SubsidyAttachment.objects.get(pk=instance.pk) + old_filename = old_attachment.attachment.name.split("/")[-1] + + if old_attachment.attachment and old_filename == instance.attachment.name: + old_attachment.attachment.delete(save=False) + + ########################### # Work hours registration # ###########################