Django - 未评估使用 "with" 模板标记缓存的变量

Django - Variable cached with "with" template tag isn't evaluated

我跟着 this article,我有一个这样的表格:

<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
<fieldset>
    <legend><h1>{{ question.question_text }}</h1></legend>
    {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
    {% for choice in question.choice_set.all %}
        <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
        <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
    {% endfor %}
</fieldset>
<input type="submit" value="Vote">
</form>

我想,由于 "choice{{ forloop.counter }}" 有多个实例,我可以在 with 模板标签内使用 with template tag and use it as a variable. But as you can see, the variable forloop.counter 缓存它未被评估。

预期的结果是这样的:

我该如何解决这个问题?

使用{{ }}的变量不能在{% %}Built-in tag[Django-doc] but we can use the variable inside {% %} if it is already available in the template. So we have to get the value before and we can set that value using with[Django-doc]中使用。但是你得到的值是动态的,每个循环你用 {{forloop.counter}} 得到新值,同样的事情我们不能在 {% %} 中使用 {{ }}。所以你可以不同地连接值,即 {{forloop.counter}}choice。 对于 concatenate 我们可以使用 add Built-in filter[Django-doc] 作为记录

Adds the argument to the value. This filter will first try to coerce both values to integers. If this fails, it’ll attempt to add the values together anyway. This will work on some data types (strings, list, etc.) and fail on others.

但是add的问题就像Warned一样

Strings that can be coerced to integers will be summed, not concatenated,

所以我们必须在连接之前先将 {{forloop.counter}} 转换为字符串,我们可以为此使用 stringformat[Django-doc] 并存储该值并将该值用作

{% for choice in question.choice_set.all %}
    {% with counter=forloop.counter|stringformat:"s" %} 
    {% with choice_id="choice"|add:counter %}
    <input type="radio" name="choice" id={{choice_id}} value="{{ choice.id }}">
    <label for={{choice_id}}>{{ choice.choice_text }}</label><br>
    {% endwith %}
    {% endwith %}
{% endfor %}