sorl-thumbnail:在模板中为for循环创建缩略图

时间:2015-06-14 20:24:11

标签: django sorl-thumbnail

我正在尝试从图片中创建大小为100x100 px的缩略图。我正在使用for循环,for循环工作并且渲染图像但由于某些原因,当我尝试创建缩略图时,它不起作用。

这是我的代码:

{% 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, )
编辑:如果我在缩略图src {{im.url}}中使用,我可以获得奇怪的图像位置。 http://127.0.0.1:8000/media/cache/9b/0b/9b0b04d65b1075ed4c3e7783131caef6.jpg,但缩略图仍未呈现。显示网址已损坏,当我尝试转到图片位置网址时,我收到404错误。

1 个答案:

答案 0 :(得分:1)

看起来你的复数位于错误的位置:

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

应该是:

{% for post_image in post.sellpostimage_set.all %}
post_image = SellPostImage.objects.filter(post=poster_posts)
context_dict['post_image'] = post_image

应该是:

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

或:

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

为什么要在模板中执行此操作:

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

如果你在上下文中有post_images吗?

这是如何运作的?

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

不应该是:

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