You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django模板中按票数用循环生成重复图片数组?

解决Django模板中根据投票数重复显示图片的问题

首先,Django模板本身没有直接支持「从0到N计数循环」的语法,但我们可以用两种简单的方式实现你的需求,完全不需要JavaScript:

方法1:利用内置ljust过滤器快速实现

这个技巧是通过生成一个长度等于choice.votes的空白字符串,然后循环遍历这个字符串的每个字符(我们不需要使用字符本身,只是借循环次数来重复渲染图片)。

修改你的模板代码如下:

<div id="Results">
    <h1>{{ question.question_text }}</h1>
    {% for choice in question.choice_set.all %}
        <div id="votes">
            <!-- 根据投票数重复显示图片 -->
            {% for _ in ''|ljust:choice.votes %}
                <img 
                    style="border-radius: 2px; border-width: 2px; border-style: none solid solid none; border-color: darkblue;" 
                    src='{{ choice.image2.url }}' 
                />
            {% endfor %}
            <div style="float: right; width: 88%;">
                <b>{{ choice.choice_text }}</b> {{ choice.votes }} vote{{ choice.votes|pluralize }}
            </div>
        </div>
    {% endfor %}
    <p id="info">Your Vote Has Been Stored!!</p>
    <br>
</div>

解释:

  • ''|ljust:choice.votes会创建一个长度与投票数一致的空白字符串,比如投票数是3的话,就生成' '(三个空格)
  • 循环里的_是占位符变量,我们不需要它的值,只是让循环执行choice.votes次

方法2:自定义模板过滤器(更优雅的方案)

如果觉得方法1的技巧不够直观,你可以创建一个自定义模板过滤器,直接返回可循环的范围对象:

  1. 在你的Django应用中创建templatetags目录(没有的话新建),并添加__init__.py和自定义过滤器文件(比如custom_filters.py)

  2. 在custom_filters.py中写入以下代码:

from django import template

register = template.Library()

@register.filter
def times(number):
    return range(number)
  1. 在模板顶部加载这个自定义过滤器:
{% load custom_filters %}
  1. 之后就可以在模板里直接用这个过滤器实现计数循环:
<div id="Results">
    <h1>{{ question.question_text }}</h1>
    {% for choice in question.choice_set.all %}
        <div id="votes">
            {% for _ in choice.votes|times %}
                <img 
                    style="border-radius: 2px; border-width: 2px; border-style: none solid solid none; border-color: darkblue;" 
                    src='{{ choice.image2.url }}' 
                />
            {% endfor %}
            <div style="float: right; width: 88%;">
                <b>{{ choice.choice_text }}</b> {{ choice.votes }} vote{{ choice.votes|pluralize }}
            </div>
        </div>
    {% endfor %}
    <p id="info">Your Vote Has Been Stored!!</p>
    <br>
</div>

这个方法代码可读性更高,适合在多个模板中重复使用。

额外注意事项

因为你的image2字段设置了blank=True(允许为空),建议在模板中添加判断,避免渲染无效的图片URL:

{% if choice.image2 %}
    {% for _ in choice.votes|times %}
        <img ... src='{{ choice.image2.url }}' />
    {% endfor %}
{% endif %}

内容的提问来源于stack exchange,提问作者arpan mahatra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:33:53