如何手动从表单集中放置表单?

时间:2019-06-07 08:32:42

标签: django

我有一个模板页面,如果数据库查询返回FALSE,它应该从表单集中加载表单。

    <form method="post" class="form">
        {% csrf_token %}

        {% for form in formset %}
        {% if comparelist.item2 %}
            <div class="col-3">{{comparelist.item2.name}}</div>
            <div class="col-3">{{comparelist.item2.price}}</div>
            <div class="col-3">{{comparelist.item2.store}}</div>            
        {% else %}
        <div>
            {{form.form-0}}
        </div>
        {% endif %}

        {% if comparelist.item3 %}
        <div class="row">
            <div class="col-3">{{comparelist.item3.name}}</div>
            <div class="col-3">{{comparelist.item3.price}}</div>
            <div class="col-3">{{comparelist.item3.store}}</div>
        </div>
        {% else %}
        <div>
            {{form.form-1}}
        </div>
        {% endif %}

        {% if comparelist.item4 %}
        <div class="row">
            <div class="col-3">{{comparelist.item4.name}}</div>
            <div class="col-3">{{comparelist.item4.price}}</div>
            <div class="col-3">{{comparelist.item4.store}}</div>
        </div>
        {% else %}
        <div>
            {{form.form-2}}
        </div>
        {%endfor%}

    <button type="submit" class="btn btn-primary">Submit</button>
    </form>

但是显然{{form.form-x}}不起作用。 那么如何手动插入这些表格?

1 个答案:

答案 0 :(得分:1)

我仍然不确定{{form.form-2}}语法应该做什么。但是我认为您想要的是直接通过表单的位置直接引用表单,就像您对comparelist项目一样。因此,删除for循环并执行以下操作:

<form method="post" class="form">
    {% csrf_token %}
    {{ formset.management_form }}

    {% if comparelist.item2 %}
        <div class="col-3">{{comparelist.item2.name}}</div>
        <div class="col-3">{{comparelist.item2.price}}</div>
        <div class="col-3">{{comparelist.item2.store}}</div>            
    {% else %}
    <div>
        {{formset.forms.0}}
    </div>
    {% endif %}

    {% if comparelist.item3 %}
    <div class="row">
        <div class="col-3">{{comparelist.item3.name}}</div>
        <div class="col-3">{{comparelist.item3.price}}</div>
        <div class="col-3">{{comparelist.item3.store}}</div>
    </div>
    {% else %}
    <div>
        {{formset.forms.1}}
    </div>
    {% endif %}

    {% if comparelist.item4 %}
    <div class="row">
        <div class="col-3">{{comparelist.item4.name}}</div>
        <div class="col-3">{{comparelist.item4.price}}</div>
        <div class="col-3">{{comparelist.item4.store}}</div>
    </div>
    {% else %}
    <div>
        {{formset.forms.2}}
    </div>
    {% endfor %}

<button type="submit" class="btn btn-primary">Submit</button>
</form>