Login

auto image field w/ prepopulate_from & default

Author:
zbyte64
Posted:
August 11, 2008
Language:
Python
Version:
.96
Score:
2 (after 2 ratings)

Given such code:

class ProductImage(models.Model):
    fullsize = models.ImageField(upload_to= "products/%Y/%m/%d/")

    display = AutoImageField(upload_to= "products/%Y/%m/%d/",prepopulate_from='fullsize', size=(300, 300))
    thumbnail = AutoImageField(upload_to="products/%Y/%m/%d/",null=True,default='/media/noimage.jpg'))

display will be automatically resized from fullsize, and thumbnail will default to /media/noimage.jpg if no image is uploaded

Note: At some point the code broke against trunk, which has now been updated to work properly

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from django.db import models
from django.db.models import signals
from django.core.files.base import ContentFile
from django.db.models.fields.files import ImageFieldFile

import cStringIO as StringIO
import Image
import os

class DefaultImageFieldFile(ImageFieldFile):
    def __init__(self, *args, **kwargs):
        super(DefaultImageFieldFile, self).__init__(*args, **kwargs)
        self.default_url = self.field.default_url
        
    def _get_url(self):
        try:
            return super(DefaultImageFieldFile, self)._get_url()
        except ValueError:
            return self.default_url
    url = property(_get_url)
    

class AutoImageField(models.ImageField):
    attr_class = DefaultImageFieldFile
    
    def __init__(self, *args, **kwargs):
        self.prepopulate_from = kwargs.pop('prepopulate_from', None)
        if self.prepopulate_from:
            self.size = kwargs.pop('size')
        self.default_url = kwargs.pop('default', None)
        if self.prepopulate_from or self.default_url:
            kwargs['blank'] = True
        super(AutoImageField, self).__init__(*args, **kwargs)
        
    def _downsize_image(self, instance, name, width, height):
        src = getattr(instance, self.prepopulate_from)
        img = Image.open(src.path)
        img = img.convert("RGB")
        img.thumbnail((width, height), Image.ANTIALIAS)
        io = StringIO.StringIO()
        img.save(io, 'JPEG')
        
        fname = os.path.split(src.path)[-1].split('.')
        fname.pop()
        fname[-1] = fname[-1] + name
        fname.append('jpg')
        fname = '.'.join(fname)
        return ContentFile(io.getvalue()), fname

    def contribute_to_class(self, cls, name):
        super(AutoImageField, self).contribute_to_class(cls, name)
        
        def process_image(instance, **kwargs):
            if not getattr(instance, name, False) and getattr(instance, self.prepopulate_from, False):
                width, height = self.size
                img, fname = self._downsize_image(instance, name, width, height)
                getattr(instance, name).save(fname, img, False)
        
        if self.prepopulate_from:
            signals.pre_save.connect(process_image, sender=cls, weak=False)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.