Search code examples
jquerydjangocheckboxdjango-templatesdjango-mptt

Checking boxes for items passed through context in Django


I am using django-mptt with the following code to display a tree structure of categories, sub-categories (and so on) with checkboxes. The idea being that the user can choose which categories to use.

{% 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>

I have the checking of the boxes working as I want (similarly to this thread), but I'm having trouble figuring out how to check the previously checked boxes from the start when the user opens the page to edit the selection.

How can I have the checkboxes checked for the node.ids I'm passing through in the context = {'selected_ids': selected_ids} when the page loads?


Solution

  • Why not do it in the template language?

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