1

I have a Django form where one of the fields is defined as:

widgets = {
    'name': forms.CheckboxSelectMultiple()
}

The template renders them in a loop with:

{% for field in form %}
    <fieldset class="article-form__field">
        {{ field.label_tag }} {{ field }}
    </fieldset>
{% endfor %}

This is rendered as:

<fieldset class="article-form__field">
    <label for="category-name_0">Category:</label>
    <ul id="category-name">
        <li><label for="category-name_0"><input id="category-name_0" name="category-name" type="checkbox" value="GEN" /> General information</label></li>
        <li><label for="category-name_1"><input id="category-name_1" name="category-name" type="checkbox" value="FOO" /> Food and drinks</label></li>
    </ul>
</fieldset>

In short: <label><input></label>. However, I would like the output to be <label></label><input>.

Is that possible, and if so, how?

Full code is here.

Flobin
  • 626
  • 1
  • 10
  • 26

1 Answers1

1
{% for field in form %}
    <fieldset class="article-form__field">
    {% if field.name != "category-name" %}
        {{ field.label_tag }} {{ field }}
    {% else %}
        {{ field.label_tag }}
        <ul id={{ field.auto_id }}>
        {% for checkbox in field %}
            <li> 
                <label for="{{ checkbox.id_for_label }}">
                    {{ checkbox.choice_label }}
                </label>
                {{ checkbox.tag }}
            </li>
        {% endfor %}
        </ul>
    {% endif %}
    </fieldset>
{% endfor %}
Vladimir Danilov
  • 2,338
  • 14
  • 15
  • Thanks so much! This solves my issue. (In my example the name is actually "name", but that's another issue.) Just one thing, what if I want to do the same with another widget? Or an arbitrary number of widgets? Could I use `{% if field.name != "category-name" and field.name != "another-name" %}`? – Flobin Jul 25 '16 at 19:13
  • @Flobin Yes, you can. I am not familar with Jinja2, but maybe you can use `{% if field.name not in ['category-name', 'another-name'] %}`. – Vladimir Danilov Jul 25 '16 at 19:30
  • Thanks so much Vladimir! – Flobin Jul 25 '16 at 19:35