如何在模板中检查ModelMultipleChoiceField中被选中的复选框

1 投票
2 回答
1683 浏览
提问于 2025-04-28 12:50
{% for choice in form.options.field.choices %}
    <div class="te">
        <label class="te">{{ choice.1 }}</label>
        <label class="te"><input type="radio" data-type="{{ text }}" name="val_{{ forloop.counter }}" value="{{ choice.0 }}" class="options" /></label>
        <label class="te"><input type="radio" data-type="{{ text }}" name="val_{{ forloop.counter }}" value="0" class="options"/></label>
    </div>
    <input class="hidden" type="checkbox" name="options" value="{{ choice.0 }}" id="val_{{ forloop.counter }}" />
{% endfor %}

上面的代码显示了标签和单选按钮,但我该如何在循环中检查哪个复选框被选中了呢?

当我使用这个 {{ form.options }} 时,它正确显示了被选中的复选框和未选中的复选框。

我在循环中尝试使用 choice.isChecked,但它总是返回真。这我该怎么解决这个问题呢?

如果我在循环中打印 choice,它会显示

(1L, u'test 1')
(2L, u'test 2')
(3L, u'test 3')
暂无标签

2 个回答

0

使用 is_checked 来检查 复选框 的状态,这对我有效。

3

更好的解释方式是通过一个代码示例,使用 if/in 来比较值:

编辑过的内容

感谢 @Anentropic 的提醒,我之前没有注意到,这里是编辑过的版本,没有使用 stringformat

{% if choice.0 in form.options.value %}selected="selected"{% endif %}

撰写回答