Inlineformset_Factory将数据保存为额外内容

时间:2019-05-12 12:51:03

标签: python django

我需要以一种形式保存2个模型。关系是外键关系。我为此使用inlineformset_factory。我想为外键表单“添加新项”。

如果inlineformset工厂:Extras = 1 当我输入外键值时;不错。 当我输入3个或更多的外键值时;只保存最后一个。

如果inlineformset_factory:附加项3 当我输入3个外键值时;不错。 但是当我尝试输入4或更多时,只能保存3个项目。

我的表格

class TestForm(ModelForm):
    class Meta:
        model = ciranta
        exclude = ()


TestFormSet = inlineformset_factory(parentModel, childModel, form=CirantaForm, extra=1)

我的观点

class TestCreate(CreateView):
    model = parentModel
    fields = ['var1','var2','var3']
    success_url = reverse_lazy('home')


    def get_context_data(self, **kwargs):
        data = super(TestCreate, self).get_context_data(**kwargs)
        if self.request.POST:
            data['childModel'] = TestFormSet(self.request.POST)
        else:
            data['childModel'] = TestFormSet()
        return data

    def form_valid(self, form):
        context = self.get_context_data()
        childModel = context['childModel']
        with transaction.atomic():
            self.object = form.save()

            if chilModel.is_valid():
                childModel.instance = self.object
                childModel.save()

        return super(TestCreate, self).form_valid(form)

我的模板:

            <table class="table">
            <br>
                {{ childModel.management_form }}

                {% for form in childModel.forms %}
                    {% if forloop.first %}
                        <thead class="thead-light">
                        <tr>
                            {% for field in form.visible_fields %}
                                <th>{{ field.label|capfirst }}</th>
                            {% endfor %}
                        </tr>
                        </thead>
                    {% endif %}
                    <tr class="{% cycle row1 row2 %} formset_row">
                        {% for field in form.visible_fields %}
                            <td>
                                {# Include the hidden fields in the form #}
                                {% if forloop.first %}
                                    {% for hidden in form.hidden_fields %}
                                        {{ hidden }}
                                    {% endfor %}
                                {% endif %}
                                {{ field.errors.as_ul }}
                                {{ field }}
                            </td>
                        {% endfor %}
                    </tr>
                {% endfor %}
            </table>

更新:在模板中

<script src="{% static 'js/jquery-1.11.0.min.js' %}"></script>
    <script src="{% static 'js/jquery.formset.js' %}"></script>
    <script type="text/javascript">
        $('.formset_row').formset({
            addText: 'Add',
            deleteText: 'Delete',
            prefix: 'test_set'
        });
    </script>

0 个答案:

没有答案