2013-02-12 30 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