首页 > 解决方案 > 如何在循环中选中多个复选框

问题描述

在一个数组中,我得到如下数组:

    ['1','2','3','4','5','6']

在另一个数组中,我得到的数组如下:

    ['1','6']

在模板中我这样做:

    <div class="col-md-10">
      {% if edit_data.features %}
    {% for feature in edit_data.feature %}
    {% for features in edit_data.features %}
    {% if feature.id == features.feature_id %}
        checked='checked'
    {%endif%}
    {%endfor%}
    <input type="checkbox" name="features" value={{feature.id}} {{checked}}> {{feature.name}}
    {%endfor%}
    {%endif%}                    
    </div>

在这之后我越来越喜欢:

我如何选择循环上的复选框我无法在 if 条件内创建变量。我是新手请让我现在如何使复选框被选中

  [1]: https://i.stack.imgur.com/LzVV4.png

在您的解决方案之后,我得到了这样的结果:

https://i.stack.imgur.com/7nZJj.png

标签: pythondjangodjango-templatesdjango-admin

解决方案


    <div class="col-md-10">
      {% if edit_data.features %}
        {% for feature in edit_data.feature %}
            {% with ns=namespace(found=false) %}
            {% for features in edit_data.features %}
                {% if feature.id == features.feature_id %}
                    {% with ns.found=true %}
                {% endif %}
            {%endfor%}
        {% if ns.found == true %}
        <input type="checkbox" name="features" value={{feature.id}}  checked> {{feature.name}}</option>
        {% else %}
           <input type="checkbox" name="features" value={{feature.id}} > {{feature.name}}</option>
        {% endif %}
        {%endfor%}
      {%endif%}                    
    </div>

推荐阅读