在 Django 中检查通过上下文传递的项目的复选框

Checking boxes for items passed through context in Django

我正在使用 django-mptt 和以下代码来显示带有复选框的类别、子类别(等等)的树结构。这个想法是用户可以选择要使用的类别。

{% load mptt_tags %}    
<ul >
{% recursetree nodes %}
    <li>
        <input type="checkbox" id="{{ node.id }}" value="{{ node.id }}"name="category"/>
        {{ node }}
        {% if not node.is_leaf_node %}
            <ul>
                {{ children }}
            </ul>
        {% endif %}
    </li>
{% endrecursetree %}
</ul>

我可以按照自己的意愿检查复选框 (similarly to this thread),但是当用户打开要编辑的页面时,我无法弄清楚如何从一开始就检查之前选中的复选框选择。

如何在页面加载时选中我在 context = {'selected_ids': selected_ids} 中经过的 node.id 的复选框?

为什么不用模板语言呢?

<input type="checkbox" {% if node.id in selected_ids %} checked="checked"{% endif %} id="{{ node.id }}" value="{{ node.id }}" name="category"/>