Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using static images with sorl-thumbnail

I am trying to serve the thumbnail of a file that resides in my STATIC_ROOT folder. It doesn't really matter if it ends up in MEDIA_URL/cache, but sorl-thumbnail will not load the image from the static folder.

current code:

{% thumbnail "images/store/no_image.png" "125x125" as thumb %}

hack that works

{% thumbnail "http://localhost/my_project/static/images/store/no_image.png" "125x125" as thumb %}

I don't like the hack because A) It is not dry (my project is actually served from a sub-directory of / B) It is using http to grab a file that is only 3 directories away, seems pointlessly inefficient

like image 783
DarwinSurvivor Avatar asked Sep 20 '11 19:09

DarwinSurvivor


3 Answers

I worked around this by passing through a file to the template context from my view.

Here is an example util function I called from my views:

def get_placeholder_image():
    from django.core.files.images import ImageFile
    from django.core.files.storage import get_storage_class
    storage_class = get_storage_class(settings.STATICFILES_STORAGE)
    storage = storage_class()
    placeholder = storage.open(settings.PLACEHOLDER_IMAGE_PATH)
    image = ImageFile(placeholder)
    image.storage = storage
    return image

You could probably do something similar as a custom template tag.

like image 156
Matt Austin Avatar answered Oct 03 '22 00:10

Matt Austin


Template filter works. But I am not sure, whether there is each time reading from storage. If so, it is unreasonably...

from django.template import Library
from django.core.files.images import ImageFile
from django.core.files.storage import get_storage_class
register = Library()

@register.filter
def static_image(path):
    """
    {% thumbnail "/img/default_avatar.png"|static_image "50x50" as img %}
        <img src="{{ MEDIA_URL }}{{img}}"/>
    {% endthumbnail %}
    """
    storage_class = get_storage_class(settings.STATICFILES_STORAGE)
    storage = storage_class()
    image = ImageFile(storage.open(path))
    image.storage = storage
    return image
like image 34
ur001 Avatar answered Oct 03 '22 00:10

ur001


Assuming you are using Django 1.3 you should take a look at the docs about Managing static files

If you setup everything correctly, you can include your images like this:

<img src="{{ STATIC_URL }}images/store/no_image.png" />
like image 43
arie Avatar answered Oct 03 '22 00:10

arie