From a3d78914a0cffc4a419554fa8103053edf05ad0d Mon Sep 17 00:00:00 2001
From: Julien Schmidt <js@stusta.net>
Date: Fri, 1 May 2020 01:01:07 +0200
Subject: [PATCH] fix saving of avatars

---
 vote/forms.py  |  4 ++--
 vote/models.py | 12 +++++++++++-
 2 files changed, 13 insertions(+), 3 deletions(-)

diff --git a/vote/forms.py b/vote/forms.py
index 32afef0..0429c91 100644
--- a/vote/forms.py
+++ b/vote/forms.py
@@ -42,7 +42,7 @@ class AccessCodeAuthenticationForm(forms.Form):
         return self.user_cache
 
 
-class CustomClearableFileInput(forms.ClearableFileInput):
+class AvatarFileInput(forms.ClearableFileInput):
     template_name = 'vote/image_input.html'
 
 
@@ -54,7 +54,7 @@ class ApplicationUploadForm(forms.ModelForm):
         self.voter = Voter.objects.get(voter_id=request.user.voter_id)
         self.request = request
 
-        self.fields['avatar'].widget = CustomClearableFileInput()
+        self.fields['avatar'].widget = AvatarFileInput()
         self.fields['first_name'].initial = self.voter.first_name
         self.fields['last_name'].initial = self.voter.last_name
         self.fields['email'].initial = self.voter.email
diff --git a/vote/models.py b/vote/models.py
index cb5769d..d17c313 100644
--- a/vote/models.py
+++ b/vote/models.py
@@ -297,6 +297,12 @@ class Application(models.Model):
     first_name = models.CharField(max_length=256)
     email = models.EmailField()
 
+    _old_avatar = None
+
+    def __init__(self, *args, **kwargs):
+        super(Application, self).__init__(*args, **kwargs)
+        self._old_avatar = self.avatar
+
     def __str__(self):
         return f'Application of {self.get_display_name()} for {self.voter.election}'
 
@@ -304,7 +310,10 @@ class Application(models.Model):
         return f'{self.first_name} {self.last_name} ({self.voter.room})'
 
     def save(self, *args, **kwargs):
-        if self.avatar:
+        if self.avatar and self._old_avatar != self.avatar:
+            if self._old_avatar and os.path.isfile(self._old_avatar.path):
+                os.remove(self._old_avatar.path)
+
             max_width = 100
             max_height = 100
             img = Image.open(self.avatar)
@@ -329,6 +338,7 @@ class Application(models.Model):
             img.save(output, format='JPEG', quality=95)
             output.seek(0)
             self.avatar = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.avatar.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None)
+            self._old_avatar = self.avatar
 
         super(Application, self).save(*args, **kwargs)
 
-- 
GitLab