muistox/gallery/models/album.py
2025-01-18 09:40:47 +02:00

52 lines
2 KiB
Python

from datetime import datetime
from django.core.exceptions import ValidationError
from django.db import models
from django.templatetags.static import static
from django.urls import reverse
from django.utils.text import slugify
from gallery.models.location import Location
class Album(models.Model):
name = models.CharField(max_length=150, unique=True, verbose_name="Album")
slug = models.SlugField(max_length=150, unique=True, verbose_name="Slug")
parent = models.ForeignKey('self', on_delete=models.SET_NULL, blank=True, null=True, limit_choices_to={'parent__isnull': True}, related_name='children', verbose_name="Parent Album")
location = models.ForeignKey(Location, blank=True, null=True, on_delete=models.SET_NULL, related_name='albums', verbose_name="Location")
album_date = models.DateField(default=datetime.now, verbose_name="Album Date")
cover = models.ForeignKey("Photo", blank=True, null=True, on_delete=models.SET_NULL, related_name='cover_to', verbose_name="Album cover")
is_public = models.BooleanField(default=False, verbose_name="Published")
@property
def photos_in_album(self):
return self.photos.count()
@property
def cover_url(self):
if self.cover:
return self.cover.photo.url
random_cover = self.photos.order_by('-width').first()
if random_cover:
return random_cover.photo.url
return static('img/placeholder.png')
def clean(self):
super().clean()
if self.parent and self.parent == self:
raise ValidationError({'parent': "An album cannot be its own parent."})
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
super(Album, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('gallery:album_url', kwargs={'album_slug': self.slug})
class Meta:
verbose_name_plural = "Albums"
ordering = ('album_date',)
def __str__(self):
return '{}'.format(self.name)