2013-02-28 72 views
0

我有一個內嵌的formset,其中extra = 24是一天中的小時。 我沒有任何問題,添加新的條目並保存編輯具有多個實例的inlineformset_factory

OreSommInlineFormSet = inlineformset_factory(FarmacoGiornaliero, OreSomministrazione, 
              form=OreForm, fields=('ore','farmaco', 'quantita'), 
              extra=24, can_delete=False)   

myospite = Ospite.objects.filter(cognome=cognome).filter(nome=nome)[0]     


if request.method == 'POST':      


    form = GiornalieroForm(request.POST) 
    formset = OreSommInlineFormSet(request.POST, prefix='formset') 

    if form.is_valid() and formset.is_valid():       


     giornaliero=form.save(commit=True)  

     for form in formset.forms: 
      ora = form.save(commit=False) 
      ora.farmaco = giornaliero 
      ora.ospite = myospite    
      ora.save()          

我試圖找出如何我可以編輯和保存的表單集的數據。我有一個查詢集,返回應該填充formset的OreFarmaco的24個實例,但formset本身只有一個instance關鍵字。

OreSommInlineFormSet = inlineformset_factory(FarmacoGiornaliero,OreSomministrazione, 形式= OreForm,字段=( '礦', 'quantita'), 額外= 24,can_delete = FALSE)

myospite = Ospite.objects.filter(cognome=cognome).filter(nome=nome)[0] 

locfarmaco = Farmaco.objects.filter(farmaco=farmaco)[0] 

giornaliero = FarmacoGiornaliero.objects.select_related() \ 
      .filter(ospite=myospite) \ 
      .filter(farmaco=locfarmaco)[0] 

orefarmaco = OreSomministrazione.objects.select_related().filter(farmaco=giornaliero).filter(ospite=myospite)   

if request.method == "POST":      

     form = GiornalieroForm(request.POST, instance=giornaliero)      

     formset = OreSommInlineFormSet(request.POST, prefix='formset', instance=orefarmaco[0]) 


     if form.is_valid() and formset.is_valid():                

      giornaliero=form.save(commit=True) 
      formset.save() 

謝謝。

回答

0
//try to rewrite this codes it's complicated. Use get() instead 
myospite = Ospite.objects.filter(cognome=cognome).filter(nome=nome)[0] 
locfarmaco = Farmaco.objects.filter(farmaco=farmaco)[0] 
giornaliero = FarmacoGiornaliero.objects.select_related() \ 
     .filter(ospite=myospite) \ 
     .filter(farmaco=locfarmaco)[0] 
// 

if request.method == "POST":      
    form = GiornalieroForm(request.POST, instance=giornaliero)      
    if form.is_valid(): 
     gio = form.save(commit=True)               
     formset = OreSommInlineFormSet(request.POST, instance=gio) 
     if formset.is_valid() 
      gio.save() 
      formset.save() 
+0

當你說get(),你的意思是使用主鍵或id來檢索數據?我的表單作爲formset的24個附加項的列表,用戶可以更改所有這些值。我怎麼能按照你所建議的方式一一處理呢? – vince 2013-02-28 16:13:01

+0

是的,但你也可以使用get in all fields。 get()函數將返回一個數據。嘗試改變過濾器來獲取。例如,像這樣:myospite = Ospite.objects.get(cognome = cognome,nome = nome) – catherine 2013-02-28 16:23:47

+0

好的,我會這麼做的。那麼formset呢?我是否必須更改我的HTML以適合您建議的鱈魚? – vince 2013-02-28 16:28:04

相關問題