2011-02-01 38 views
1

另一個複選框的問題。我有一個列表中的項目。每個項目都有一個複選框。我想要做的是在列表中勾選FIRST項目的複選框。請注意,由於checked="checked",它勾選了所有複選框。Django複選框只想檢查第一個框

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

回答

1

你可以選中屬性添加到第二個項目是這樣的:

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

默認forloop.counter爲1索引,或者您可以專門使用0索引計數器:

forloop.counter0 
1

The forloop variable通過Django的{% for %}標籤設置在這裏你的朋友。

流行這個在:

{% 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 %} 
+0

確定這工作謝謝。還有一件事,如果我想檢查我的清單中的第二項。我無法輸入{%if forloop.second%},所以我應該輸入什麼內容? – Shehzad009 2011-02-01 15:52:57

+0

@ Shehzad009:當然,那會是`{%if forloop.counter == 2%}`。您可以在文檔中看到`{%for%}`標記的其他功能:http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for – 2011-02-01 16:58:34

相關問題