gault-millau/apps/gallery/models.py
2019-12-20 17:27:04 +03:00

60 lines
1.8 KiB
Python

from django.db import models
from django.utils.translation import gettext_lazy as _
from sorl import thumbnail
from sorl.thumbnail.fields import ImageField as SORLImageField
from utils.methods import image_path
from utils.models import ProjectBaseMixin, SORLImageMixin, PlatformMixin
class ImageQuerySet(models.QuerySet):
"""QuerySet for model Image."""
class Image(ProjectBaseMixin, SORLImageMixin, PlatformMixin):
"""Image model."""
HORIZONTAL = 0
VERTICAL = 1
ORIENTATIONS = (
(HORIZONTAL, _('Horizontal')),
(VERTICAL, _('Vertical')),
)
image = SORLImageField(upload_to=image_path,
verbose_name=_('image file'))
orientation = models.PositiveSmallIntegerField(choices=ORIENTATIONS,
blank=True, null=True, default=None,
verbose_name=_('image orientation'))
title = models.CharField(_('title'), max_length=255, default='')
objects = ImageQuerySet.as_manager()
class Meta:
"""Meta class."""
verbose_name = _('Image')
verbose_name_plural = _('Images')
ordering = ['-modified']
def __str__(self):
"""String representation"""
return f'{self.id}'
def delete_image(self, completely: bool = True):
"""
Deletes an instance and crops of instance from media storage.
:param completely: if set to False then removed only crop neither original image.
"""
try:
# Delete from remote storage
thumbnail.delete(file_=self.image.file, delete_file=completely)
except FileNotFoundError:
pass
finally:
if completely:
# Delete an instance of image
super().delete()