0

这可能是一个相当简单的问题。但我正在尝试使用从数据库中获取的初始数据填充我的表单。我真的不知道从哪里开始。任何建议都会有所帮助。

一些背景:我患有多种指标的疾病。在我的表单中,我正在提取 disease_id = 2 然后想要填充数据库中当前的指标,以便可以对其进行编辑。

视图.py

def drui(request):

disease_id = request.GET.get('disease_id', '2')

    if request.method == "POST":

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

       if diseaseForm.is_valid():
          new_disease = diseaseForm.save(commit=False)
          indicatorInlineFormSet = IndicatorFormSet(request.POST, request.FILES, instance=new_disease)

          if indicatorInlineFormSet.is_valid():
             new_disease.save()
             indicatorInlineFormSet.save()
             return HttpResponseRedirect(reverse(somewhere))

     else:
       diseaseForm = DiseaseForm()
       indicatorInlineFormSet = IndicatorFormSet(instance=Disease())

    return render_to_response("drui.html", {'diseaseForm': diseaseForm, 'indicatorInlineFormSet': indicatorInlineFormSet},context_instance=RequestContext(request))   
4

1 回答 1

1

只需将疾病对象放在请求 POST 中即可

def drui(request):
    disease_id = request.GET.get('disease_id', '2')
    disease = get_object_or_404(Disease, pk=disease_id)

    if request.method == "POST":
       diseaseForm = DiseaseForm(request.POST, instance=disease)
       if diseaseForm.is_valid():
          new_disease = diseaseForm.save(commit=False)
          indicatorInlineFormSet = IndicatorFormSet(request.POST, request.FILES, 
                                                    instance=new_disease)
          if indicatorInlineFormSet.is_valid():
             new_disease.save()
             indicatorInlineFormSet.save()
             return HttpResponseRedirect(reverse(somewhere))
    else:
       diseaseForm = DiseaseForm(instance=disease)
       indicatorInlineFormSet = IndicatorFormSet(instance=disease)

    return render_to_response("drui.html", {
        'diseaseForm': diseaseForm, 
        'indicatorInlineFormSet': indicatorInlineFormSet
    },context_instance=RequestContext(request))   
于 2013-08-04T09:24:08.153 回答