2013-02-12 35 views
0

我使用Django Forms製作html表單。我使用BoundFields,因爲我的表單佈局中有一些特殊的東西。Django Forms BoundField - 遍歷ChoiceField時沒有id標記的輸出

我在窗體中有一個RadioSelect小部件的ChoicesField。我手動遍歷的選擇,因爲我想把<li>內的IMG:

<ul> 
    {% for country in form.country %} 
     <li> 
      <img src="{{ MEDIA_URL }}country_icons/country_{{ country.value }}.png"> 
      {{ country }} 
     </li> 
    {% endfor %} 
</ul> 

但現在的輸出不包括輸入元素ID標籤:

<ul> 
    <li> 
     <img src="/media/country_icons/country_nl.png"> 
     <label> 
      <input type="radio" value="nl" name="country" checked="checked"> 
      Netherlands 
     </label> 
    </li> 
    <li> 
     <img src="/media/country_icons/country_de.png"> 
     <label> 
      <input type="radio" value="de" name="country"> 
      Germany 
     </label> 
    </li> 
</ul> 

然而,當我不會遍歷選項,只是輸出領域:

{{ form.country }} 

將輸出:

<ul> 
    <li> 
     <label for="id_country_0"> 
      <input id="id_country_0" type="radio" value="nl" name="country" checked="checked"> 
      Netherlands 
     </label> 
    </li> 
    <li> 
     <label for="id_country_1"> 
      <input id="id_country_1" type="radio" value="de" name="country"> 
      Germany 
     </label> 
    </li> 
</ul> 

所以我的問題是,當我手動迭代選擇時,id字段不存在。這使得我的CSS/JavaScript選擇器不一致。

所以我的問題是,是否有某種方式來包含ID標籤呢? 無論如何,這是行爲?或者這可能是一個錯誤?任何人遇到類似的問題?

回答

1

我不知道它爲什麼這樣工作。我的猜測是,這些id是由form api創建的迭代器創建的。一個國家不知道迭代器(它可能出現在模板中而不出現在for循環中),因此無法創建id。

要回答你的其他問題 - 是的,你可以自己構建輸入以包含id。

像 -

{% for country in form.country %} 
    <li> 
     <img src="{{ MEDIA_URL }}country_icons/country_{{ country.value }}.png"> 
     <label for="id_country_{{ forloop.counter0 }}"> 
      <input id="id_country_{{ forloop.counter0 }}" type="radio" value="{{ country.value }}" name={{ country }}> 
     </label> 
     {{ country.name }} 
    </li> 
{% endfor %} 

看一看在文檔上template for loops