Search code examples
djangoimagesorl-thumbnail

Creating thumbnails inside a for loop in Django template


I am facing a very strange (maybe silly) error. I am trying to generate thumbnails inside a for loop like this:

{% for u in users %}

    <img src="{{ u.avatar.url }}" />
    {% thumbnail "{{ u.avatar.url }}" "200x200" crop="center" as im %}
        <img src="{{im.url}}" width="{{im.width}}" height="{{im.height}}">
    {% endthumbnail %}

{% endfor %}

The images exist because the first img tag appear with the original image, but the cropped image is broken because of the src provided (E.g: /media/cache/ab/9e/ab9ec80287d675891def81e7f07b819c.jpg) does not exist in my computer.

Log messages

Another weird thing I´ve noticed is that all the users have the img tag with the same path. In this case I have two users, and this is the code I get rendered:

<img src="/media/images/profile/img.jpg" alt="" />
<img src="/media/cache/ab/9e/ab9ec80287d675891def81e7f07b819c.jpg" width="" height="">
<img src="/media/images/profile/avatar.jpeg" alt="" />
<img src="/media/cache/ab/9e/ab9ec80287d675891def81e7f07b819c.jpg" width="" height="">

Solution

  • You need to get rid of the {{ }}. Also, you should pass the image object to the template tag; not just the URL:

    {% thumbnail u.avatar "200x200" crop="center" as im %}
    

    More in the docs.