Formset从formset中保存第一个表单

时间:2016-03-09 16:04:54

标签: django python-3.x django-forms

当我想在一个模型中保存所有表单时,我遇到了麻烦。因为形成所有我生成的东西只是先保存。所以我的帖子请求是我的输出形式。

> csrfmiddlewaretoken    mL6ecbCqW8RA1oFH1AiDzv40tsRW0Esj form-0-count   1
> form-0-good    5 form-1-count  1 form-1-good   6 form-2-count  1
> form-2-good    12 form-INITIAL_FORMS   0 form-MAX_NUM_FORMS    1000
> form-MIN_NUM_FORMS     0 form-TOTAL_FORMS  3

所以我的views.py

@login_required
def index(request):
    if request.user.role == '2':
        shop = Shop.objects.get(owner=request.user.parent)
        goods = Good.objects.filter(shop=shop, count__gt=0)
        saleformset = formset_factory(SaleForm)
        if request.method == 'POST':
            formset = saleformset(request.POST)
            for form in formset:
                form.fields['good'].queryset = goods
            for form in formset.forms:
                a = 0

                print(formset)
                print(len(formset))

                if form.is_valid():
                    print(form.is_valid())
                    a += 1
                    print(a)
                    new_form = form.save(commit=False)
                    new_form.seller = request.user
                    new_form.save()
                    good_object = Good.objects.get(pk=new_form.good.pk)
                    own_count = good_object.count - new_form.count
                    good_object = Good.objects.filter(pk=new_form.good.pk).\
                        update(count=own_count)
                    return render(request, 'all_ok.html', {'data': 'lil'})
        else:
            formset = saleformset()
            for form in formset:
                form.fields['good'].queryset = goods

        return render(request, 'base_vendor.html',
                      {'context': goods, 'formset': formset})

page.html中

{% load staticfiles %}
<script src="https://code.jquery.com/jquery-2.2.1.min.js" > </script>
<script src="{% static 'js/gener.js' %}" > </script>



<script type="text/javascript">
    <!--
    $(function () {
        $('.add-row').click(function() {
            return addForm(this, 'form');
        });
        $('.delete-row').click(function() {
            return deleteForm(this, 'form');
        })
    })
    //-->
    </script>
<form action="" method="post">
    {% csrf_token %}
    <table id="id_forms_table" border="0" cellpadding="0" cellspacing="5">
        <tbody>{% load staticfiles %}
<script src="https://code.jquery.com/jquery-2.2.1.min.js" > </script>
<script src="{% static 'js/gener.js' %}" > </script>



<script type="text/javascript">
    <!--
    $(function () {
        $('.add-row').click(function() {
            return addForm(this, 'form');
        });
        $('.delete-row').click(function() {
            return deleteForm(this, 'form');
        })
    })
    //-->
    </script>
<form action="" method="post">
    {% csrf_token %}
    <table id="id_forms_table" border="0" cellpadding="0" cellspacing="5">
        <tbody>
            {% for form in formset.forms %}
            <tr id="{{ form.prefix }}-row" class="dynamic-form">
                <td>{{ form.as_p }}</td>
                    <a id="remove-{{ form.prefix }}-row" href="javascript:void(0)" class="delete-row"></a>
                </td>
            </tr>
            {% endfor %}
            <tr>
                <td colspan="4"><a href="javascript:void(0)" class="add-row">add property</a></td>
            </tr>
        </tbody>
    </table>
    {{ formset.management_form }}
    <div>
        <input type="submit" value="Find " />
    </div>
    </form>
        {% for form in formset.forms %}
        <tr id="{{ form.prefix }}-row" class="dynamic-form">
            <td>{{ form.as_p }}</td>
                <a id="remove-{{ form.prefix }}-row" href="javascript:void(0)" class="delete-row"></a>
            </td>
        </tr>
        {% endfor %}
        <tr>
            <td colspan="4"><a href="javascript:void(0)" class="add-row">add property</a></td>
        </tr>
    </tbody>
</table>
{{ formset.management_form }}
<div>
    <input type="submit" value="Find " />
</div>
</form>

视图中的print`s输出。

<input id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="3" /><input id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0" /><input id="id_form-MIN_NUM_FORMS" name="form-MIN_NUM_FORMS" type="hidden" value="0" /><input id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000" />
<tr><th><label for="id_form-0-good">Good:</label></th><td><select id="id_form-0-good" name="form-0-good">
<option value="">---------</option>
<option value="5" selected="selected">Nazva test4</option>
<option value="6">NAzva 2 test4</option>
<option value="12">terter tert ert ert</option>
</select></td></tr>
<tr><th><label for="id_form-0-count">Count:</label></th><td><input id="id_form-0-count" min="0" name="form-0-count" type="number" value="1" /></td></tr> <tr><th><label for="id_form-1-good">Good:</label></th><td><select id="id_form-1-good" name="form-1-good">
<option value="">---------</option>
<option value="5">Nazva test4</option>
<option value="6" selected="selected">NAzva 2 test4</option>
<option value="12">terter tert ert ert</option>
</select></td></tr>
<tr><th><label for="id_form-1-count">Count:</label></th><td><input id="id_form-1-count" min="0" name="form-1-count" type="number" value="1" /></td></tr> <tr><th><label for="id_form-2-good">Good:</label></th><td><select id="id_form-2-good" name="form-2-good">
<option value="">---------</option>
<option value="5">Nazva test4</option>
<option value="6">NAzva 2 test4</option>
<option value="12" selected="selected">terter tert ert ert</option>
</select></td></tr>
<tr><th><label for="id_form-2-count">Count:</label></th><td><input id="id_form-2-count" min="0" name="form-2-count" type="number" value="1" /></td></tr>
3
True
1

1 个答案:

答案 0 :(得分:0)

那是因为你正在使用

return render(request, 'all_ok.html', {'data': 'lil'})

作为for form in formset.forms循环的最后一条陈述。这导致视图在保存其他表单之前返回。你需要在for循环之后移动这个语句。

for form in formset.forms:
    a = 0

    print(formset)
    print(len(formset))

    if form.is_valid():
        print(form.is_valid())
        a += 1
        print(a)
        new_form = form.save(commit=False)
        new_form.seller = request.user
        new_form.save()
        good_object = Good.objects.get(pk=new_form.good.pk)
        own_count = good_object.count - new_form.count
        good_object = Good.objects.filter(pk=new_form.good.pk).\
            update(count=own_count)
return render(request, 'all_ok.html', {'data': 'lil'})