编辑与父表单关联的inlineformsets

时间:2014-12-17 18:53:24

标签: python django inline-formset

我使用Modelform和inlineforset_factory在其中创建了发票和商品。 现在我正在尝试创建编辑表单,但是当我尝试编辑这些内联字段时,我得到了MultiValueDictKeyError。如果我只是创建新的inlineformsets,我可以很好地编辑Modelform。经过一小时的谷歌搜索后,我无法找到任何解决方案。

maxItems = 20
ItemFormSet = inlineformset_factory(Invoice, Item, can_delete=True, extra=maxItems)

创建新发票(完美运作)

def new_invoice(request):
if request.method == "POST":
    form = InvoiceForm(request.POST)
    if form.is_valid():
        invoice = form.save(commit=False)
        item_formset = ItemFormSet(request.POST,instance=invoice)
        if item_formset.is_valid():
            invoice.dateCreated = datetime.datetime.now()
            invoice.save()
            item_formset.save()
            return redirect('list/new0')
else:
    form = InvoiceForm()
    item_formset = ItemFormSet(instance=Invoice())
return render(request, "form.html", {"form": form, "item_formset": item_formset })

编辑发票(MultiValueDictKeyError)

def edit_invoice(request, invoice_id):
invoicer = get_object_or_404(Invoice, pk=invoice_id)
if request.method == "POST":
    form = InvoiceForm(request.POST, instance=invoicer)
    if form.is_valid():
        invoice = form.save(commit=False)
        item_formset = ItemFormSet(request.POST,instance=invoice)
        if item_formset.is_valid():
            invoice.dateCreated = datetime.datetime.now()
            invoice.save()
            item_formset.save()
            return redirect('list/new0')
else:
    form = InvoiceForm(instance=invoicer)
    item_formset = ItemFormSet(instance=invoicer)
return render(request, "form.html", {"form": form, "item_formset": item_formset })

2 个答案:

答案 0 :(得分:0)

我有两个变量invoicerinvoice,我假设它们是同一个对象的不同实例。尝试重写您的编辑视图,如下所示:

def edit_invoice(request, invoice_id):
    invoice = get_object_or_404(Invoice, pk=invoice_id)
    if request.method == 'POST':
        form = InvoiceForm(request.POST, instance=invoice)
        formset = ItemFormSet(request.POST, instance=invoice)
        if form.is_valid() and formset.is_valid():
            invoice = form.save()
            invoice.dateCreated = datetime.datetime.now()
            invoice.save()
            formset.save()
            return redirect('list/new0')
    else:
        form = InvoiceForm(instance=invoice)
        formset = ItemFormSet(instance=invoice)
    context = {
      'form': form,
      'formset': formset,
    }
    return render(request, 'form.html', context)

请告诉我这是否适合您。

答案 1 :(得分:0)

好的,所以我发现问题不在views.py中,也不在forms.py中,而是在模板中。因为我在不使用{{form.as_p / table / ...}}的情况下构建了模板。表单有一些额外的输入 - DELETE,ID和foreignKey ...将它们添加到我的for循环后,一切正常:)