sorl-thumbnail: Creating a thumbnail inside a for loop in a template

305 views Asked by At

I am trying to create a thumbnail with the size of 100x100 px from an image. I am using a for loop, and the for loops works and the image is rendered but for some reason when I am trying to create a thumbnail it doesn't work.

Here is my code:

{% for post_images in post.sellpostimage_set.all %}
           <img class="thumbnail" src="{{ post_images.pictures.url }}" />

            {% thumbnail post_images "100x100" crop="center" as im %}
                <img src="{{ im.pictures.url }}" width="{{ im.width }}" height="{{ im.height }}">
            {% endthumbnail %}

{% endfor %}

views.py

def post(request, post_name_slug):
    context_dict = {}
    try:

        post = SellPost.objects.get(slug=post_name_slug)
        context_dict['post'] = post

        poster_posts = SellPost.objects.filter(user=post.user).order_by('-timestamp')
        context_dict['poster_posts'] = poster_posts

        post_image = SellPostImage.objects.filter(post=poster_posts)
        context_dict['post_image'] = post_image

        poster = post.user
        context_dict['poster'] = poster

    except SellPost.DoesNotExist:
        return redirect('index')
    return render(request, 'post.html', context_dict, )

EDIT: If I use in the thumbnail src {{ im.url }} I can get the Image location which is weird.. http://127.0.0.1:8000/media/cache/9b/0b/9b0b04d65b1075ed4c3e7783131caef6.jpg , but again the thumbnail image is still not being rendered. Shows as the URL is broken, and when I try to go to the image location url I get a 404 error.

1

There are 1 answers

2
François Constant On BEST ANSWER

It looks like your plural are in the wrong spot:

{% for post_images in post.sellpostimage_set.all %}

should be:

{% for post_image in post.sellpostimage_set.all %}

post_image = SellPostImage.objects.filter(post=poster_posts)
context_dict['post_image'] = post_image

should be:

post_images = SellPostImage.objects.filter(post=poster_posts)
context_dict['post_images'] = post_images

or:

post_image = SellPostImage.objects.get(post=poster_posts)
context_dict['post_image'] = post_image

why do you do this in your template:

{% for post_images in post.sellpostimage_set.all %}

if you have post_images in the context?


How does this work?

<img class="thumbnail" src="{{ post_images.pictures.url }}" />

shouldn't it be:

<img class="thumbnail" src="{{ post_image.picture.url }}" />