Search code examples
pythondjangodjango-formsjinja2multi-model-forms

edit django form widget rendering


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.


Solution

  • {% 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 %}