我们遇到了同样的错误。
这个错误的原因:每次这个 StdImage 实例初始化它的 .thumbnail 字段时,它都会调用self.generate_filename
来获取它的文件名,然后在文件名中插入一个“.thumnail”作为缩略图的名称。
资源:
def _set_thumbnail(self, instance=None, **kwargs):
"""Creates a "thumbnail" object as attribute of the ImageField instance
Thumbnail attribute will be of the same class of original image, so
"path", "url"... properties can be used
"""
if getattr(instance, self.name):
filename = self.generate_filename(instance,
os.path.basename(getattr(instance, self.name).path))
thumbnail_filename = self._get_thumbnail_filename(filename)
thumbnail_field = ThumbnailField(thumbnail_filename)
setattr(getattr(instance, self.name), 'thumbnail', thumbnail_field)
当路径不是动态的时,它是正确的。但是当我们使用动态路径时headimg = models.FileField(upload_to='headimg/%Y%m')
,返回的self.generate_filename
对应的是今天的日期,所以thumbnail.path每天都在变化。
快速解决:
在 stdimage/fields/py 的源代码中
def _set_thumbnail(self, instance=None, **kwargs):
"""Creates a "thumbnail" object as attribute of the ImageField instance
Thumbnail attribute will be of the same class of original image, so
"path", "url"... properties can be used
"""
if getattr(instance, self.name):
#fix the bug of wrong thumbnail path
#filename = self.generate_filename(instance,
# os.path.basename(getattr(instance, self.name).path))
file_path = getattr(instance, self.name).path
file_prefix = self.upload_to[:self.upload_to.find('/')]
filename = file_path[file_path.find(file_prefix):]
thumbnail_filename = self._get_thumbnail_filename(filename)
thumbnail_field = ThumbnailField(thumbnail_filename)
setattr(getattr(instance, self.name), 'thumbnail', thumbnail_field)
这个对我有用。
我向 github 上的 stdimage 项目提交了一个问题。希望作者改正。