2013-02-08 23:15:00 +00:00
|
|
|
from ...cachefiles import ImageCacheFile
|
2012-10-16 03:53:05 +00:00
|
|
|
from django.db.models.fields.files import ImageField
|
2012-02-14 02:47:53 +00:00
|
|
|
|
|
|
|
|
|
2012-02-17 23:39:51 +00:00
|
|
|
class ImageSpecFileDescriptor(object):
|
2012-02-14 02:47:53 +00:00
|
|
|
def __init__(self, field, attname):
|
|
|
|
|
self.attname = attname
|
|
|
|
|
self.field = field
|
|
|
|
|
|
|
|
|
|
def __get__(self, instance, owner):
|
|
|
|
|
if instance is None:
|
|
|
|
|
return self.field
|
|
|
|
|
else:
|
2012-12-01 21:46:10 +00:00
|
|
|
field_name = getattr(self.field, 'source', None)
|
2012-10-16 03:53:05 +00:00
|
|
|
if field_name:
|
2012-12-12 03:53:13 +00:00
|
|
|
source = getattr(instance, field_name)
|
2012-10-16 03:53:05 +00:00
|
|
|
else:
|
2012-11-06 04:34:32 +00:00
|
|
|
image_fields = [getattr(instance, f.attname) for f in
|
|
|
|
|
instance.__class__._meta.fields if
|
2012-10-16 03:53:05 +00:00
|
|
|
isinstance(f, ImageField)]
|
|
|
|
|
if len(image_fields) == 0:
|
2012-11-06 04:34:32 +00:00
|
|
|
raise Exception('%s does not define any ImageFields, so your'
|
|
|
|
|
' %s ImageSpecField has no image to act on.' %
|
2012-10-16 03:53:05 +00:00
|
|
|
(instance.__class__.__name__, self.attname))
|
|
|
|
|
elif len(image_fields) > 1:
|
2012-11-06 04:34:32 +00:00
|
|
|
raise Exception('%s defines multiple ImageFields, but you'
|
2012-12-01 21:46:10 +00:00
|
|
|
' have not specified a source for your %s'
|
2012-10-16 03:53:05 +00:00
|
|
|
' ImageSpecField.' % (instance.__class__.__name__,
|
|
|
|
|
self.attname))
|
|
|
|
|
else:
|
2012-12-12 03:53:13 +00:00
|
|
|
source = image_fields[0]
|
2013-01-24 02:35:38 +00:00
|
|
|
spec = self.field.get_spec(source=source)
|
2013-02-08 23:15:00 +00:00
|
|
|
file = ImageCacheFile(spec)
|
2012-10-17 03:51:26 +00:00
|
|
|
instance.__dict__[self.attname] = file
|
|
|
|
|
return file
|
2012-02-18 01:07:50 +00:00
|
|
|
|
|
|
|
|
def __set__(self, instance, value):
|
|
|
|
|
instance.__dict__[self.attname] = value
|