我对Django很新,所以这可能是一个容易的问题.我有两个modelForms,其中有一个ForeignKey到另一个.我的主要目标是将指标与疾病(FK)联系起来,使得对于特定的疾病,您可以有多个指标.
使用下面的代码,当我点击提交“管理窗体数据丢失或被篡改”时,我收到错误.此外,views.py中的代码似乎没有在第三个’if’语句中返回HttpResponseRedirect的验证.但是,当我检查我的数据库时,表单中的值已写入.任何关于为什么错误提出的想法?以及如何解决?
我的代码如下:
models.py
#Table for Disease class Disease(models.Model): disease = models.CharField(max_length=300) #Tables for Indicators class Indicator(models.Model): relevantdisease = models.ForeignKey(Disease) indicator = models.CharField(max_length=300)
forms.py
class DiseaseForm(forms.ModelForm): class Meta: model = Disease class IndicatorForm(forms.ModelForm): class Meta: model = Indicator DiseaseFormSet = inlineformset_factory(Disease,Indicator,can_delete=False,form=DiseaseForm)
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('some_url.html') else: indicatorForm = IndicatorForm() diseaseInlineFormSet = DiseaseFormSet() return render_to_response("drui.html",{'indicatorForm': indicatorForm,'diseaseInlineFormSet': diseaseInlineFormSet},context_instance=RequestContext(request))
template.html
<form class="disease_form" action="{% url drui %}" method="post">{% csrf_token %} {{ indicatorForm.as_table }} <input type="submit" name="submit" value="Submit" class="button"> </form>
解决方法
您的模板中既没有diseaseFormSet也没有formFormSet的管理表单,但是您尝试实例化表单集. Formsets需要隐藏的管理表单,告诉django集合中有多少个表单.
将其插入到HTML中
{{ diseaseFormSet.as_table }} {{ diseaseFormSet.management_form }}