From 7f2760d4ccfb00dff4e85b97610ad157d892179a Mon Sep 17 00:00:00 2001 From: Frederic Date: Fri, 22 Nov 2013 10:40:09 +0100 Subject: [PATCH] added 'image' field to Product, uploaded images get scaled automatically (can be configured through THUMBNAIL_SIZE in settings.py) --- cash/models.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/cash/models.py b/cash/models.py index e955c63..2395443 100644 --- a/cash/models.py +++ b/cash/models.py @@ -1,3 +1,5 @@ + +from django.conf import settings from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save @@ -6,6 +8,7 @@ from django.dispatch import receiver from django_auth_ldap.backend import populate_user from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_noop +import PIL class Account(models.Model): user = models.OneToOneField(User) @@ -109,6 +112,8 @@ class Product(models.Model): active = models.BooleanField(default = True, verbose_name = _('active')) category = models.ForeignKey(ProductCategory, blank=True, null=True, verbose_name = _('category')) + image = models.ImageField(upload_to="products", verbose_name = _('image'), + blank=True, null=True) def __unicode__(self): return self.name @@ -117,6 +122,21 @@ class Product(models.Model): verbose_name = _('product') verbose_name_plural = _('products') +@receiver(post_save, sender=Product) +def product_post_save_handler(sender, instance, **kwargs): + img = instance.image + if img: + img.open(mode='r') + with img: + scaled = PIL.Image.open(img) + thumbnail_size = getattr(settings, 'THUMBNAIL_SIZE', (150, 150)) + scaled.thumbnail(thumbnail_size, PIL.Image.ANTIALIAS) + + img.open(mode='w') + with img: + scaled.save(img) + + class ProductBarcode(models.Model): barcode = models.CharField(max_length=32, unique=True, verbose_name = _('barcode'))