开发者

Django: CheckboxSelectMultiple

Is it possible to render each checkbox individually, instead of it having to clump all the checkboxes together in a list, as it does by default? Something like

{{ myform.cbmultiple.0 }}

To render just the first checkbox? Actually the 0 would have to be a variable so I can loop...

The reason I'm asking is because I want to display these checkboxes in a rather complicated way, so the default widget doesn't work for me. I also 开发者_如何学JAVAdon't really want to override the widget because it's much easier to render it using the template syntax than in python code, plus, that's a lot of work for a one-off.


No you can't do that because the whole HTML is generated by the widget's render method at once. You could only create your own widget class and override the render method so that it produces the HTML in a fashion that suits your purpose!


There is a way to render the CheckboxSelectMultiple() manually in the template so you can do what you want with it.

Take a look at this post for details.

The solution could be something like this:

<table>
<thead>
  <tr>
  <td>&nbsp;</td>
  <td>V</td>
  <td>S</td>
  </tr>
</thead>    
{% for pk, choice in form.options.field.widget.choices %}
<tr>
<td><a href="/link/{{ choice }}">{{ choice }}</a></td>
<td><label for="id_options_{{ forloop.counter0 }}"><input {% for option in app.options.all %}{% if option.pk == pk %}checked="checked"{% endif %}{% endfor %} type="checkbox" id="id_options_{{ forloop.counter0 }}" value="{{ pk }}" name="options" /></label></td>
</tr>
{% endfor %}                
</table>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜