4

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.

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

Comments

3

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!

7 Comments

That's awful :\ I find Django forms make my life a lot harder, not easier. I think I'll boycott the damn widget and render it myself with straight HTML then nab it off request.POST instead.
Well you're right, though it would be just a few lines of python. It is still horrible that the HTML is inside the widget classes and not using any kind of template!
Yeah.. it's the (lack of) separation of logic and presentation that I don't like. I want all the view stuff in one place, because I know I'm going to tweak the look a whole bunch more.
You can at least iterate over the field's choices in the template and present it in the way you want to... Something like {% for c in form.cbmultiple.field.choices %}Value: {{ c.0 }}, Text: {{ c.1 }} {% endfor %}.
Might be a good solution. However I didn't find a way to display the input boxes ! Did you ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.