Search code examples
djangojsonthumbnailseasy-thumbnails

Django easy_thumbnails accessing image URLs


Is it possible to access the URLs of easy_thumbs created images?

I have a model with an ImageField and a ModelForm to match.

# models.py

class ModelWithAnImage(models.Model):
    image = ThumbnailerImageField(
        upload_to='images',
    )

Following the documentation I am using signals to generate two thumbs when the image is uploaded.

# somewherethatdefinitelygetsloaded.py

from easy_thumbnails.signals import saved_file
from easy_thumbnails.signal_handlers import generate_aliases_global


saved_file.connect(generate_aliases_global)

This is working fine but is it possible to then access the url for those thumbs?

.

model_with_an_image.image.url returns the original image (as you'd expect).

The aim is to send the thumb url via AJAX to an external source so the {% thumbnail %} is not going to help me at the moment.

# requirements.txt

Django==1.5.1
Pillow==2.0.0
boto==2.9.0
django-storages==1.1.8
easy-thumbnails==1.2

Solution

  • The documentation points to the thumbnail_url template filter, which can return the URL of a thumnail inside a template.

    You can call the template filter like a real function from your view (or anywhere else), and it should work just as fine as in a template, e.g.:

    from easy_thumbnails.templatetags.thumbnail import thumbnail_url
    
    thumbnail_url = thumbnail_url(model_with_an_image, 'small')
    

    Behind the scenes, the filter just calls get_thumbnailer so you could also write:

    thumbnailer = get_thumbnailer(model_with_an_image)
    thumbnailer.generate = False  # so a not generate a thumb if sthg went wrong
    thumbnail = thumbnailer.get_thumbnail(thumbnail_options)
    #  do stuff with thumbnail.url