Search code examples
pythondjangosorl-thumbnail

How can change or override sorl-thumbnail cache path and add image with absolute path?


I have and mediaservice website and my file storage is in other folder from media folder and I want to cache thumbnails in the other folder, How can I change sorl-thumbnail cache folder and How can I give image with absolute path to make thumbnail ?


Solution

  • Take a look at the class responsible for naming thumbnails produced by sorl-thumbnail.

    You could subclass it and use your custom class as your thumbnail backend:

    # in your settings.py:
    THUMBNAIL_BACKEND = 'path.to.MyThumbnailBackend'
    
    
    #some module, in one of yours apps:
    from sorl.thumbnail.base import ThumbnailBackend
    from sorl.thumbnail.conf import settings
    from sorl.thumbnail.helpers import tokey, serialize
    
    class MyThumbnailBackend(ThumbnailBackend):
        def _get_thumbnail_filename(self, source, geometry_string, options):
            """
            Computes the destination filename.
            """
            key = tokey(source.key, geometry_string, serialize(options))
            # make some subdirs
            path = '%s/%s/%s' % (key[:2], key[2:4], key)
            return '%s%s.%s' % (settings.THUMBNAIL_PREFIX, path,
                                EXTENSIONS[options['format']])
    

    The previous snippet was the original code of _get_thumbnail_filename. You can tweak this code to generate the name at your convenience.