【问题标题】:Django checkbox want to check only the first boxDjango复选框只想选中第一个框
【发布时间】:2011-06-19 08:47:41
【问题描述】:

另一个复选框问题。我在列表中有项目。每个项目都有一个复选框。我想要做的是在列表中勾选 FIRST 项目的复选框。没错,因为checked="checked",它已经勾选了所有的复选框。

{% for item in items %}
            <tr class="items_table_row">
                    <td><input type="checkbox" name="{{item.pk}}" value="{{item.pk}}" checked="checked"></td>
                    <td>{{item.tiptop_id}}</td><td>{{item.alternative_id}}</td><td>{{item.title}}</td><td>{{item.type}}</td><td>{{item.format}}</td>
                    <td><span id="{{item.pk}}" name="type">{{item.itemstatushistory_set.latest}}</span></td><td>{{item.itemstatushistory_set.latest.date.date|date:"d M Y"}}</td>
                    <td><a href="{% url tiptop.views.edit_item item.client.pk item.pk %}" onclick="return showAddAnotherPopup(this);">Edit</a></td>
            </tr>
    {% endfor %}

【问题讨论】:

    标签: python html django checkbox views


    【解决方案1】:

    您可以像这样将选中的属性添加到第二项:

    {% ifequal forloop.counter 2 %} checked="checked"{% endifequal %}
    

    默认forloop.counter是1-indexed,或者你可以专门使用0-indexed counter:

    forloop.counter0
    

    【讨论】:

    • 供参考 - 从 Django 1.2(甚至可能是 1.1)开始,{% ifequal forloop.counter 2 %} 可以重写为 {% if forloop.counter == 2 %}
    【解决方案2】:

    由 Django {% for %} 标签设置的The forloop variable 是你的朋友。

    弹出这个:

    {% if forloop.first %} checked="checked"{% endif %}
    

    {% for item in items %}
         <tr class="items_table_row">
            <td><input type="checkbox" name="{{item.pk}}" value="{{item.pk}}"{% if forloop.first %} checked="checked"{% endif %}></td>
            <td>{{item.tiptop_id}}</td><td>{{item.alternative_id}}</td><td>{{item.title}}</td><td>{{item.type}}</td><td>{{item.format}}</td>
            <td><span id="{{item.pk}}" name="type">{{item.itemstatushistory_set.latest}}</span></td><td>{{item.itemstatushistory_set.latest.date.date|date:"d M Y"}}</td>
            <td><a href="{% url tiptop.views.edit_item item.client.pk item.pk %}" onclick="return showAddAnotherPopup(this);">Edit</a></td>
        </tr>
    {% endfor %}
    

    【讨论】:

    • 好的,谢谢。如果我只想检查列表中的第二项,还有一件事。我无法输入 {% if forloop.second %} 那我应该输入什么?
    • @Shehzad009:当然,那是{% if forloop.counter == 2 %}。您可以在文档中查看{% for %} 标签的其他功能:docs.djangoproject.com/en/dev/ref/templates/builtins/#for
    猜你喜欢
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 2022-07-11
    • 2023-03-13
    • 2011-06-19
    • 2013-10-21
    相关资源
    最近更新 更多