Changed filenames to UUID4 which are thrown into a single directory. Added auto-delete for changed / deleted PlaceImages.
This commit is contained in:
parent
1c401532ad
commit
3c92bc93cd
@ -1,4 +1,9 @@
|
|||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
|
||||||
from django.db import models
|
from django.db import models
|
||||||
|
from django.dispatch import receiver
|
||||||
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
# Create your models here.
|
# Create your models here.
|
||||||
|
|
||||||
@ -13,9 +18,44 @@ class Place (models.Model):
|
|||||||
return self.name
|
return self.name
|
||||||
|
|
||||||
class PlaceImage (models.Model):
|
class PlaceImage (models.Model):
|
||||||
filename = models.ImageField(upload_to='places/%Y/%m/', max_length=50)
|
filename = models.ImageField(
|
||||||
|
upload_to=lambda instance, filename: 'places/' + str(uuid.uuid4()),
|
||||||
|
max_length=50
|
||||||
|
)
|
||||||
place = models.ForeignKey(Place, on_delete=models.CASCADE, related_name='images')
|
place = models.ForeignKey(Place, on_delete=models.CASCADE, related_name='images')
|
||||||
description = models.TextField(blank=True)
|
description = models.TextField(blank=True)
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return ' '.join([self.place.name, str(self.pk)])
|
return ' '.join([self.place.name, str(self.pk)])
|
||||||
|
|
||||||
|
# These two auto-delete files from filesystem when they are unneeded:
|
||||||
|
|
||||||
|
@receiver(models.signals.post_delete, sender=PlaceImage)
|
||||||
|
def auto_delete_file_on_delete(sender, instance, **kwargs):
|
||||||
|
"""
|
||||||
|
Deletes file from filesystem
|
||||||
|
when corresponding `PlaceImage` object is deleted.
|
||||||
|
"""
|
||||||
|
if instance.filename:
|
||||||
|
if os.path.isfile(instance.filename.path):
|
||||||
|
os.remove(instance.filename.path)
|
||||||
|
|
||||||
|
@receiver(models.signals.pre_save, sender=PlaceImage)
|
||||||
|
def auto_delete_file_on_change(sender, instance, **kwargs):
|
||||||
|
"""
|
||||||
|
Deletes old file from filesystem
|
||||||
|
when corresponding `PlaceImage` object is updated
|
||||||
|
with new file.
|
||||||
|
"""
|
||||||
|
if not instance.pk:
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
old_file = PlaceImage.objects.get(pk=instance.pk).filename
|
||||||
|
except PlaceImage.DoesNotExist:
|
||||||
|
return False
|
||||||
|
|
||||||
|
new_file = instance.filename
|
||||||
|
if not old_file == new_file:
|
||||||
|
if os.path.isfile(old_file.path):
|
||||||
|
os.remove(old_file.path)
|
||||||
|
Loading…
Reference in New Issue
Block a user