我正在尝试在我的表单中添加额外的行,但它似乎被忽略了。我有一个类似的设置django inlineformset_factory extra attribute being ignored?但没有基本模型。我试图实施该解决方案,但没有成功。有没有人有解决方案在我的表单中添加额外的行?
这是我的代码:
Models.py
class Disease(models.Model):
disease = models.CharField(max_length=300, verbose_name="disease")
def __unicode__(self):
return self.disease
class Indicator(models.Model):
relevantdisease = models.ForeignKey(Disease, verbose_name="disease")
indicator = models.CharField(max_length=300, verbose_name="indicators")
def __unicode__(self):
return self.indicator
Forms.py
MAX_INDICATORS = 3
class DiseaseForm(forms.ModelForm):
class Meta:
model = Disease
class IndicatorForm(forms.ModelForm):
class Meta:
model = Indicator
DiseaseFormSet = inlineformset_factory(Disease,
Indicator,
can_delete=False,
extra=MAX_INDICATORS,
form=DiseaseForm)
IndicatorFormSet = inlineformset_factory(Indicator,
IndicatorValue,
can_delete=False,
extra=MAX_INDICATORS,
form=IndicatorForm)
Views.py
def drui(request):
if request.method == "POST":
indicatorForm = IndicatorForm(request.POST)
if indicatorForm.is_valid():
new_indicator = indicatorForm.save()
diseaseInlineFormSet = DiseaseFormSet(request.POST, request.FILES, instance=new_indicator)
if diseaseInlineFormSet.is_valid():
diseaseInlineFormSet.save()
return HttpResponseRedirect(reverse(something))
else:
indicatorForm = IndicatorForm()
diseaseInlineFormSet = DiseaseFormSet()
return render_to_response("something.html", {'indicatorForm': indicatorForm, 'diseaseInlineFormSet': diseaseInlineFormSet},context_instance=RequestContext(request))
更新了代码: 现在,1种疾病将与多种指标联系起来,我可以获得额外的线条。但是,现在的问题是,每当我保存指标并从数据库中选择疾病时,一种新的疾病将被写入链接到指标的数据库。
Views.py
def drui(request):
if request.method == "POST":
diseaseForm = DiseaseForm(request.POST)
if diseaseForm.is_valid():
new_disease = diseaseForm.save(commit=False)
indicatorInlineFormSet = IndicatorFormSet(request.POST, instance=new_disease)
if indicatorInlineFormSet.is_valid():
new_disease.save()
indicatorInlineFormSet.save()
return HttpResponseRedirect(reverse(valdrui))
else:
diseaseForm = DiseaseForm()
indicatorInlineFormSet = IndicatorFormSet(instance=Disease())
return render_to_response("drui.html", {'diseaseForm': diseaseForm, 'indicatorInlineFormSet': indicatorInlineFormSet},context_instance=RequestContext(request))
forms.py
class DiseaseForm(forms.ModelForm):
disease = forms.ModelChoiceField(queryset=Disease.objects.all())
class Meta:
model = Disease
class IndicatorForm(forms.ModelForm):
class Meta:
model = Indicator
IndicatorFormSet = inlineformset_factory(Disease,
Indicator,
can_delete=False,
extra=MAX_INDICATORS)
HTML:
{{ diseaseForm.as_table }}
{{ indicatorInlineFormSet.as_table }}
答案 0 :(得分:1)
在您的视图中,您只有一个IndicatorForm
用于单个Indicator
个实例,还有一个DiseaseFormSet
可将多个Disease
个实例绑定到该Indicator
个实例。但是在您的models.py中,您有ForeignKey
Indicator
到Disease
,这意味着Indicator
只能绑定到一个Disease
个实例,而Disease
实例可以包含任意数量的Indicators
。
要解决此问题,请将ForeignKey
从Indicator
模型更改为Disease
模型,更改为Disease
模型中的Indicator
模型 - 或者如果您想要反过来,请坚持使用您已获得的模型,并使用IndicatorFormSet
和DiseaseForm
。