0

我患有一种与多种指标相关的疾病。我的问题是,每当我保存指标并从下拉列表中选择一种疾病时,都会将一种新疾病写入链接到指标的数据库中。

我想要一个从我的疾病表中采样的下拉菜单。用户选择一种疾病并输入指标。指标保存在指标表中,并带有指向疾病表中疾病的链接(而不是在疾病表中写入新疾病)。

我将此作为参考参考:http ://charlesleifer.com/blog/djangos-inlineformsetfactory-and-you/

视图.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)) 

表格.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 }}

更新: 我使用 Mariodev 的建议让它工作,但前提是我输入 PK=1 或其他一些硬编码数字。如何通过用户选择的PK?选择来自 PK = id 的疾病表。这是我的views.py的片段:

def drui(request, id):

    if request.method == "POST":


       disease = get_object_or_404(Disease, pk=id)
       diseaseForm = DiseaseForm(request.POST, instance=disease)

       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))

当我点击提交时出现此错误:drui() 恰好需要 2 个参数(给定 1 个)。有什么建议么?

4

1 回答 1

0

是的,我的第一个建议是错误的。您应该做的是在编辑视图中显示 inlineformset,这样您就可以使用现有对象创建 DiseaseForm 的实例。所以而不是:

diseaseForm = DiseaseForm(request.POST)

你做:

disease = get_object_or_404(Disease, pk=disease_id)
diseaseForm = DiseaseForm(request.POST, instance=disease)

disease_id 取自 url

于 2013-08-03T22:00:43.940 回答