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
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.
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
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With