lostplaces-backend/source/lostplaces/lostplaces_app/models.py

80 lines
2.3 KiB
Python
Raw Normal View History

import os
import uuid
2020-07-19 00:13:49 +02:00
from django.db import models
from django.dispatch import receiver
from django.contrib.auth.models import AbstractUser
from django_thumbs.fields import ImageThumbsField
2020-07-19 00:13:49 +02:00
# Create your models here.
# Custom user model
class Explorer(AbstractUser):
# add additional fields in here
def __str__(self):
return self.username
# Place defines a lost place (location, name, description etc.).
2020-07-19 00:13:49 +02:00
class Place (models.Model):
name = models.CharField(max_length=50)
location = models.CharField(max_length=50)
latitude = models.FloatField()
longitude = models.FloatField()
description = models.TextField()
def __str__(self):
return self.name
# Define callback that generates /path/to/image.ext as filename.
2020-07-28 09:39:11 +02:00
def generate_image_upload_path(instance, filename):
return 'places/' + str(uuid.uuid4())+'.'+filename.split('.')[-1]
class PlaceImage (models.Model):
filename = ImageThumbsField(
2020-07-28 09:39:11 +02:00
upload_to=generate_image_upload_path,
max_length=50,
sizes=(
{'code': 'thumbnail', 'wxh': '390x390'},
{'code': 'hero', 'wxh': '700x700'},
{'code': 'large', 'wxh': '1920x1920'}
)
)
place = models.ForeignKey(Place, on_delete=models.CASCADE, related_name='images')
description = models.TextField(blank=True)
def __str__(self):
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)