1
from django.db import models
3
from django.template.defaultfilters import slugify
5
from PIL.Image import core as _imaging
6
from cStringIO import StringIO
7
from django.core.files.uploadedfile import SimpleUploadedFile, UploadedFile
8
from django.core.files.storage import FileSystemStorage
10
from settings import THUMBNAIL_SIZE, MEDIA_ROOT
11
from django.urls import reverse
14
# Taken from django snippet 976
16
class OverwriteStorage(FileSystemStorage):
18
def get_available_name(self, name, max_length=None):
19
"""Returns a filename that's free on the target storage system, and
20
available for new content to be written to."""
21
# If the filename already exists, remove it as if it was a true file
24
os.remove(os.path.join(MEDIA_ROOT, name))
28
class Category(models.Model):
29
name = models.CharField(max_length=255)
30
slug = models.SlugField(max_length=255, unique=True, blank=True)
32
def save(self, *args, **kwargs):
34
self.slug = slugify(self.name)
36
return super(Category, self).save(*args, **kwargs)
38
def get_absolute_url(self):
39
return reverse('wlscreens_category', kwargs={'category_slug': self.slug})
41
def __unicode__(self):
42
return u"%s" % self.name
45
def screenshot_path(instance, filename):
46
return 'wlscreens/screens/%s/%s.%s' % (
47
instance.category, instance.name, filename.rsplit('.', 1)[-1].lower()
51
def thumbnail_path(instance, filename):
52
return 'wlscreens/thumbs/%s/%s.png' % (
53
instance.category, instance.name)
56
class Screenshot(models.Model):
57
name = models.CharField(max_length=255)
59
screenshot = models.ImageField(
60
upload_to=screenshot_path,
61
storage=OverwriteStorage(),
63
thumbnail = models.ImageField(
64
upload_to=thumbnail_path,
66
storage=OverwriteStorage(),
68
comment = models.TextField(null=True, blank=True)
69
category = models.ForeignKey(Category, related_name='screenshots')
72
unique_together = ('name', 'category')
74
def save(self, *args, **kwargs):
75
# Open original screenshot which we want to thumbnail using PIL's Image
77
image = Image.open(self.screenshot)
79
# Convert to RGB if necessary
80
if image.mode not in ('L', 'RGB'):
81
image = image.convert('RGB')
83
image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
86
temp_handle = StringIO()
87
image.save(temp_handle, 'png')
90
# Save to the thumbnail field
91
suf = SimpleUploadedFile(os.path.split(self.screenshot.name)[-1],
92
temp_handle.read(), content_type='image/png')
93
self.thumbnail.save(suf.name + '.png', suf, save=False)
95
# Save this photo instance
96
super(Screenshot, self).save(*args, **kwargs)
98
def __unicode__(self):
99
return u"%s:%s" % (self.category.name, self.name)