我定义了一个函数 _set_thumbnail 将属性附加到对象。
class StdImageField(ImageField):
def __init__(self, verbose_name=None, name=None, width_field=None,
height_field=None, sizes=None, **kwargs):
self.sizes = sizes
super(StdImageField, self).__init__(verbose_name, name, width_field,
height_field, **kwargs)
def contribute_to_class(self, cls, name):
"""Call methods for generating all operations on specified signals"""
super(StdImageField, self).contribute_to_class(cls, name)
signals.post_save.connect(self.resize_image, sender=cls)
signals.post_init.connect(self._set_thumbnail, sender=cls)
def resize_image(self, instance=None, **kwargs):
if getattr(instance, self.name):
filename = getattr(instance, self.name).path
shutil.copyfile(filename, '%s/%d-0.jpg' % (os.path.dirname(filename), instance._get_pk_val()))
for i, size in enumerate(self.sizes):
img = Image.open(filename)
img = ImageOps.fit(img, size, method=Image.ANTIALIAS)
new_filename = '%s/%d-%d.jpg' % (os.path.dirname(filename), instance._get_pk_val(), i + 1)
img.save(new_filename, "JPEG", quality=100)
def _set_thumbnail(self, instance=None, **kwargs):
if getattr(instance, self.name):
for i, size in enumerate(self.sizes):
setattr(getattr(instance, self.name), 'image%d' % (i + 1), '%s%d-%d.jpg' % ('s/', instance._get_pk_val(), i + 1))
它可以通过 Django admin 完美运行。但是,在通过前端使用它时出现错误:
TypeError( %d 格式:需要一个数字,而不是 NoneType )
任何建议将不胜感激。谢谢。