Image handling refined (filenames, mobile rendering)
All checks were successful
Build containers when image tags change / build-if-image-changed (., web, containers, main container, git.baumann.gr/adebaumann/labhelper) (push) Successful in 1m9s
Build containers when image tags change / build-if-image-changed (data-loader, loader, initContainers, init-container, git.baumann.gr/adebaumann/labhelper-data-loader) (push) Successful in 56s
All checks were successful
Build containers when image tags change / build-if-image-changed (., web, containers, main container, git.baumann.gr/adebaumann/labhelper) (push) Successful in 1m9s
Build containers when image tags change / build-if-image-changed (data-loader, loader, initContainers, init-container, git.baumann.gr/adebaumann/labhelper-data-loader) (push) Successful in 56s
This commit is contained in:
@@ -1,7 +1,19 @@
|
||||
import os
|
||||
from django.db import models
|
||||
from django.utils.text import slugify
|
||||
from mptt.models import MPTTModel, TreeForeignKey
|
||||
|
||||
|
||||
def thing_picture_upload_path(instance, filename):
|
||||
"""Generate a custom path for thing pictures in format: <id>-<name>.<extension>"""
|
||||
extension = os.path.splitext(filename)[1]
|
||||
safe_name = slugify(instance.name)
|
||||
if instance.pk:
|
||||
return f'things/{instance.pk}-{safe_name}{extension}'
|
||||
else:
|
||||
return f'things/temp-{safe_name}{extension}'
|
||||
|
||||
|
||||
class BoxType(models.Model):
|
||||
"""A type of storage box with specific dimensions."""
|
||||
|
||||
@@ -72,10 +84,29 @@ class Thing(models.Model):
|
||||
related_name='things'
|
||||
)
|
||||
description = models.TextField(blank=True)
|
||||
picture = models.ImageField(upload_to='things/', blank=True)
|
||||
picture = models.ImageField(upload_to=thing_picture_upload_path, blank=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ['name']
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
"""Override save to rename picture file after instance gets a pk."""
|
||||
if self.picture and not self.pk:
|
||||
picture = self.picture
|
||||
super().save(*args, **kwargs)
|
||||
new_path = thing_picture_upload_path(self, picture.name)
|
||||
if picture.name != new_path:
|
||||
try:
|
||||
old_path = self.picture.path
|
||||
if os.path.exists(old_path):
|
||||
new_full_path = os.path.join(os.path.dirname(old_path), os.path.basename(new_path))
|
||||
os.rename(old_path, new_full_path)
|
||||
self.picture.name = new_path
|
||||
super().save(update_fields=['picture'])
|
||||
except (AttributeError, FileNotFoundError):
|
||||
pass
|
||||
else:
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
Reference in New Issue
Block a user