在Django / Python中设置属性时出错

时间:2012-09-11 11:25:21

标签: python django

我定义了一个将属性附加到对象的函数_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管理员完美无瑕地工作。然而,当通过前端使用它时,我得到了一个错误:

TypeError(%d格式:需要一个数字,而不是NoneType)

任何建议都将不胜感激。 谢谢。

0 个答案:

没有答案