2014-11-17 75 views
0

我從數據庫中檢索數據,並在模板中顯示它們對應的表單。然後,當我嘗試更新字段時,這些表單不會提交檢索到的數據,因此表單未經驗證。在表單中顯示的檢索數據無法在django中正確提交

你有什麼想法如何解決這個問題?

views.py

def results(request): 

    context = RequestContext(request) 
    myid = request.GET.get('id', '') 
    diag_option = 0 
    print "my id", myid 
    if request.method == 'POST': 
     my_demographics = DemographicForm(request.POST or None, prefix="demo") 

     if my_demographics.is_valid(): 
      my_demographics_object = my_demographics.save() 

    else: 

     patient = Demographic.objects.get(patient_id = myid) 

     my_demographics = DemographicForm(instance=form_data)  

    return render_to_response('input.html', {'frm':my_demographics}, context) 

模板results.html

<form class="form-horizontal" method="post" id="input"> 
    {% csrf_token %} 

    <div class="tab-pane" id="mytab"> 
     <div class="tab-content"> 
      <div class="tab-pane fade in active" id="1"> 
       <!--<input type="hidden" name="form_id" value="demographics">--> 
       <div class="container"> {%crispy frm%}</div> 

      </div> 
     </div> 
    </div> 
</form> 

forms.py

class DemographicForm(forms.ModelForm): 

    def __init__(self, *args, **kwargs): 
     super(DemographicForm, self).__init__(*args, **kwargs) 
     self.helper=FormHelper(self) 
     self.fields['date_of_birth'].widget = widgets.AdminDateWidget() 
     self.helper.layout = Layout(
      'national_health_care_pat_id', 
      'patient_hospital_file_number', 
      'patient_id', 
      'given_name', 
      'surname', 
      'date_of_birth', 

      FormActions(
       Submit('submit', "Save changes"), 
       Submit('cancel', "Cancel") 
      ), 

     ) 
     self.helper.form_tag = False 
     self.helper.form_show_labels = True 

    class Meta: 
     model = Demographic 
     exclude = [] 

的方式做我檢索數據問題?

我在另一個模板中使用上述代碼來查找患者。

patient = Demographic.objects.select_for_update().filter(patient_id = myid) 
+0

能否請你減少你的代碼到最低位置:其中,該視圖中的多種形式導致了問題?它仍然發生在一個單一的形式?你也應該發佈表單本身的代碼。 –

+0

@DanielRoseman是的,你是對的!完成! – zinon

+0

表單沒有任何操作,所以除非您將它發佈到相同的網址上,否則將無法使用。 –

回答

0

我找到了解決方案,在@brunodesthuilliers解決方案上工作!

問題是我必須通過instance=patient,即使在request.POST之後,爲了讓django知道將數據作爲更新來處理。

views.py

def results(request): 

    context = RequestContext(request) 
    myid = request.GET.get('id', '') 

    if request.method == 'POST': 
     with transaction.atomic(): 
      patient = Demographic.objects.get(patient_id=myid) 

     my_demographics = DemographicForm(request.POST or None, instance=patient) 

     if my_demographics.is_valid(): 
      my_demographics_object = my_demographics.save() 

    else: 
     with transaction.atomic(): 
      print "HERE ELSE" 
      patient = Demographic.objects.get(patient_id=myid) 

     my_demographics = DemographicForm(instance=patient) 

    return render_to_response('input.html', {'frm':my_demographics}, context) 
相關問題