Django:inlineformset_factory不更新完整数据,但可以向现有数据添加新数据

时间:2016-04-23 05:31:03

标签: django django-forms django-views

我使用inlineformset_factory来保存数据。我能够添加数据,编辑现有数据。 问题是编辑我可以添加更多订单项,但如何删除现有订单项?

Views.py

@login_required
def edit_invoice(request,pk):    
    product = serviceinvoice.objects.get(pk=pk)
    if product.user != request.user:
        raise PermissionDenied
    new_formset=createinvoiceformsetedit(instance=product)
    if request.method == 'POST':        
        inv_form=createinvoiceformedit(user=request.user,data=request.POST,instance=product)        
        if inv_form.is_valid():
            new_form=inv_form.save(commit=False)
            new_form.user=request.user
            new_formset=createinvoiceformsetedit(request.POST,instance=new_form)
            if new_formset.is_valid():
                new_form.save()
                hero=new_formset.save(commit=False)
                for hero1 in hero:
                    hero1.user=request.user
                    hero1.save()
                return HttpResponseRedirect(reverse('invoicelist'),{'section':'editinvoice'})
    else:
        inv_form=createinvoiceformedit(request.user,instance=product)
    return render(request,'account/editinvoice.html',{'inv_form':inv_form,'new_formset':new_formset})

我可以在渲染表中看到删除检查选项,但即使选择删除检查选项,也不会删除数据并显示字段必需错误。

1 个答案:

答案 0 :(得分:0)

通过尝试不同的事情得到答案。

解决方案:

def edit_invoice(request,pk):    
    product = serviceinvoice.objects.get(pk=pk)
    if product.user != request.user:
        raise PermissionDenied
    new_formset=createinvoiceformset(instance=product)
    if request.method == 'POST':        
        inv_form=createinvoiceform(user=request.user,data=request.POST,instance=product)        
        if inv_form.is_valid():
            new_form=inv_form.save(commit=False)
            new_form.user=request.user
            new_formset=createinvoiceformset(request.POST,instance=new_form)
            if new_formset.is_valid():
                new_form.save()
                try:
                    new_formset.save()
                except:
                    hero=new_formset.save(commit=False)
                    for hero in hero:
                        hero.user=request.user
                        hero.save()
                return HttpResponseRedirect(reverse('invoicelist'),{'section':'editinvoice'})
    else:
        inv_form=createinvoiceform(request.user,instance=product)
    return render(request,'account/editinvoice.html',{'inv_form':inv_form,'new_formset':new_formset})

解决方案

try:, except: worked like a charm.