Sending the url of a thumbnail from Django with sorl.thumbnail

written by Herman Schaaf on Jan. 16, 2011
Find me on Twitter, Google+ or LinkedIn

Sorl.thumbnail is a fantastic (in my opinion the best) thumbnailing library for Django. The documentation isn't all that great though, and it takes some figuring out how to actually send just an URL string from Django to the template, instead of using the template tag (which is normally very useful). "Why would one want to avoid the template tag?", you might ask. Well, for one, when sending JSON information back through Ajax. Then there is no template, only javascript rendering, so you need this feature. 

Having justified why, here is how to send the thumbnail url of a resized image as a string:

from sorl.thumbnail.main import DjangoThumbnail

img = imageObject # a normal image url returned from an ImageField
size = (100,100) # any tuple 
img_resize_url = unicode(DjangoThumbnail(img, size))

Then you can simply return the img_resize_url variable with your other Json (or normal) variables.



If you found this post interesting, you might also like our blog post, Django: It's DRY, but you can sink your teeth into it