mpen
mpen

Reputation: 283273

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 don'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.

Upvotes: 4

Views: 4553

Answers (2)

Below the Radar
Below the Radar

Reputation: 7635

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>

Upvotes: 3

Bernhard Vallant
Bernhard Vallant

Reputation: 50796

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!

Upvotes: 3

Related Questions