我对 Django 比较陌生,所以这可能是一个简单的问题。我有 2 个 modelForms,其中有一个 ForeignKey。我的主要目标是保存带有疾病 (FK) 链接的指标,这样对于特定疾病,您可以拥有多个指标。
使用下面的代码,当我点击提交时出现错误,提示“ManagementForm 数据丢失或已被篡改”。此外,views.py 中的代码似乎没有在第三个“if”语句中进行验证,其中有一个返回 HttpResponseRedirect。但是,当我检查我的数据库时,表单中的值已被写入。关于为什么提出错误的任何想法?以及如何解决?
我的代码如下:
模型.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)
表格.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)
视图.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))
模板.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>