Django formset渲染3个formsets

时间:2017-12-13 18:04:23

标签: python django

我已经制作了一个更新模型客户端和模型ClientData的formset,我的问题是,它不是渲染一个formset,而是渲染它3次,我无法识别原因。

views.py

def client_data(request):
    data = dict()
    if request.method == "POST":
        form = ClientForm(request.POST)
        if form.is_valid():
            client = form.save(commit=False)
            formset = ClientFormSet(request.POST, instance=client)
            if formset.is_valid():
                client.save()
                formset.save()
                return redirect(reverse_lazy('core:index'))
    else:
        form = ClientForm()
        formset = ClientFormSet()
    data['form'] = form
    data['formset'] = formset
    return render(request, 'core/test.html', data)

forms.py

class ClientForm(ModelForm):

    class Meta:
        model = Client
        fields = '__all__'
        exclude = ['user', ]


class ClientDataForm(ModelForm):

    class Meta:
        model = ClientData
        fields = '__all__'
        exclude = ['client', ]


ClientFormSet = inlineformset_factory(Client, ClientData, fields=[
    'language',
    'type',
])

模板

<form method="POST">{% csrf_token %}
    {{ form.as_p }}
    {{ formset }}
    <button type="submit" class="save btn btn-default">Save</button>
</form>

1 个答案:

答案 0 :(得分:1)

根据文档,使用 inlineformset_factory 构建表单集,在inlineformset中,默认情况下为额外选项,为3。

试试这个:

inlineformset_factory(Client, ClientData, fields=[
    'language',
    'type',
],
extra=1)

https://docs.djangoproject.com/en/1.11/ref/forms/models/#inlineformset-factory