[Answer]-Django-stdimage dynamic file structure

1👍

We met the same bug.

Cause of this bug: every time this StdImage instance init its .thumbnail field, it calls self.generate_filename to get its filename, then insert an ‘.thumnail’ into filename as name of thumbnail.

Source:

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)

It’s right when the path is not dynamic. But when we use dynamic path such as headimg = models.FileField(upload_to='headimg/%Y%m'), return of self.generate_filename is corresponding to the date of today, so the thumbnail.path is changed every day.

Quick Fix:

In the source of 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)

It works for me.

I submitted an issue to the stdimage project on github. Hope the author will fixed it.

Leave a comment