django-imagekit/imagekit/models/fields/utils.py
Matthew Tretter 12493b3a0d Spec host must support kwarg "hints"
The registry's `get_spec()` was already supporting kwargs as a means to
provide information about the source to the spec constructor/factory
function, but the ``SpecHost`` class wasn't capable of accepting any.
This commit rectifies that. The main goal purpose of this is to allow a
bound field (the file attached by ``ImageSpecFileDescriptor``)--and the
attached model instance--to be taken into account during the spec
instance creation.

Related: #156
2012-10-20 23:29:07 -04:00

38 lines
1.6 KiB
Python

from ...files import ImageSpecCacheFile
from django.db.models.fields.files import ImageField
class ImageSpecFileDescriptor(object):
def __init__(self, field, attname):
self.attname = attname
self.field = field
def __get__(self, instance, owner):
if instance is None:
return self.field
else:
field_name = getattr(self.field, 'image_field', None)
if field_name:
source_file = getattr(instance, field_name)
else:
image_fields = [getattr(instance, f.attname) for f in \
instance.__class__._meta.fields if \
isinstance(f, ImageField)]
if len(image_fields) == 0:
raise Exception('%s does not define any ImageFields, so your' \
' %s ImageSpecField has no image to act on.' % \
(instance.__class__.__name__, self.attname))
elif len(image_fields) > 1:
raise Exception('%s defines multiple ImageFields, but you' \
' have not specified an image_field for your %s' \
' ImageSpecField.' % (instance.__class__.__name__,
self.attname))
else:
source_file = image_fields[0]
spec = self.field.get_spec() # TODO: What "hints" should we pass here?
file = ImageSpecCacheFile(spec, source_file)
instance.__dict__[self.attname] = file
return file
def __set__(self, instance, value):
instance.__dict__[self.attname] = value