GZ_0
GZ_0

Reputation: 27

Fixing ManagementForm-data

I have some code which looks like this:

<table>
    {% for n in model %}
        {% for i in formset.forms %}
            {% if forloop.parentloop.counter == forloop.counter %}
                <tr>
                <th>{{ n }}</th>
                {% for j in i %}
                    <th>{{ j }}</th>
                {% endfor %}
                </tr>
            {% endif %}
        {% endfor %}
    {% endfor %}
</table>

I really want to keep it this way, because this is the presentation I've been asked for. However, I keep getting the "ManagementForm-data missing or tampered with" error, obviously because I'm messing with the formset.

Is there a smart way to fix the managementform-data so my POST will go through, or do I have to reformat my template completely?

(Yes, I am aware that my code contains an ugly, inefficient hack. Please feel free to suggest an alternative, but performance doesn't matter.)

Upvotes: 0

Views: 31

Answers (1)

Alasdair
Alasdair

Reputation: 308899

You get the error about missing management form data because you haven't included the management form with {{ formset.management_form }}. See the docs for more info.

To prevent the double loop in the template, you can zip model and formset.forms in the view:

models_and_forms = zip(model, formset.forms)

Then loop through the models_and_forms in the template:

<table>
    {{ formset.management_form }}
    {% for n, i in models_and_forms %}
        <tr>
            <th>{{ n }}</th>
            {% for j in i %}
                <th>{{ j }}</th>
            {% endfor %}
        </tr>
    {% endfor %}
</table>

Upvotes: 2

Related Questions