我有一个内联formset,其中extra = 24是一天中的小时数。 添加新条目并保存
没有任何问题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的数据。我有一个查询集,它返回24个OreFarmaco实例,它们应该填充formset,但是formset本身只有一个instance关键字预设了一个实例。
OreSommInlineFormSet = inlineformset_factory(FarmacoGiornaliero,OreSomministrazione, form = OreForm,fields =('ore','quantita'), extra = 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 :(得分: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()