2016-04-23 67 views
0

我正在使用inlineformset_factory保存數據。我可以添加數據,編輯現有數據。 問題在編輯中我可以添加更多訂單項,但如何刪除現有訂單項?Django: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

的[在Django動態刪除直列表單集]可能的複製(http://stackoverflow.com/questions/2357059/dynamically-delete-inline- formsets-in-django) – solarissmoke

+0

@solarissmoke更新後的問題。我可以看到刪除檢查選項,但它不起作用。即使在選擇刪除檢查選項後,也會顯示字段所需的錯誤。 –

+0

這不會自動發生 - 您需要讓客戶端站點的Javascript設置要刪除的字段。這就是爲什麼我鏈接到的帖子建議使用django-dynamic-formset。 – solarissmoke

回答

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. 
相關問題