Django easy_thumbnails accessing image URLs

一笑奈何 提交于 2020-01-23 09:56:16

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/16174675/django-easy-thumbnails-accessing-image-urls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!