I am using Django Rest framework. I have three fields in my Pin Model : image,thumbnail_medium and thumbnail_small. I want to create two thumbnails from the image. How to do that? I tried the following code : But it's not working.
from django.db import models
from django.contrib.auth.models import User
from thumbs import ImageWithThumbsField
#from taggit.managers import TaggableManager
from PIL import Image
from cStringIO import StringIO
from django.core.files.uploadedfile import SimpleUploadedFile
import os
class Pin(models.Model):
url = models.SlugField(blank=True, null=True)
title = models.TextField(blank=False,null=False,default='Untitled')
description = models.TextField(blank=True, null=True)
is_pro = models.BooleanField(default=False)
is_hidden = models.BooleanField(default=False)
is_for_sale = models.BooleanField(default=False)
is_pro = models.BooleanField(default=False)
price = models.DecimalField(blank=True, null=True, max_digits=10, decimal_places=2 ,default=0)
price_in_rs = models.BooleanField(default=False)
size_in_inches = models.BooleanField(default=True)
medium = models.TextField(blank=True, null=True)
length = models.DecimalField(blank=True, null=True, max_digits=10, decimal_places=2 ,default=0)
width = models.DecimalField(blank=True, null=True, max_digits=10, decimal_places=2 ,default=0)
hearts = models.IntegerField(blank=True, null=True, default=0)
image = models.ImageField(upload_to='pins/pin/originals/')
thumbnail = models.ImageField(upload_to='pins/pin/thumbnails/')
published = models.DateTimeField(auto_now_add=True)
#tags = TaggableManager()
def __unicode__(self):
return self.url
def save(self):
from PIL import Image
from cStringIO import StringIO
from django.core.files.uploadedfile import SimpleUploadedFile
# Set our max thumbnail size in a tuple (max width, max height)
THUMBNAIL_SIZE = (50, 50)
# Open original photo which we want to thumbnail using PIL's Image
# object
image = Image.open(
self.image.name)
# Convert to RGB if necessary
# Thanks to Limodou on DjangoSnippets.org
#
http://www.djangosnippets.org/snippets/20/ if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
# We use our PIL Image object to create the thumbnail, which already
# has a thumbnail() convenience method that contrains proportions.
# Additionally, we use Image.ANTIALIAS to make the image look better.
# Without antialiasing the image pattern artifacts may result.
image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
# Save the thumbnail
temp_handle = StringIO()
image.save(temp_handle, 'png')
temp_handle.seek(0)
# Save to the thumbnail field
suf = SimpleUploadedFile(os.path.split(
self.image.name)[-1],
temp_handle.read(), content_type='image/png')
self.thumbnail.save(
suf.name+'.png', suf, save=False)
# Save this photo instance
super(Pin, self).save()
Can anyone figure out the problem here? Why is it not creating thumbnails?