2017-09-24 48 views
0

我的表單我有幾個下拉鍊接在它們之間用AJAX。嘗試使用django表單保存時,動態構建AJAX下拉列表將重置爲原始狀態?

這是怎樣一個我填充它們

function getleaseterm() { 

     //get a reference to the select element 
     $select = $('#id_leaseterm'); 
     //request the JSON data and parse into the select element 
     var l_id = ($("select[name='lease'] option:selected").attr('value')); 
     //var l_id = 13; 
     l_url = "/api/get_leaseterm/"+l_id+"/"; 

     $.ajax({ 
      url: l_url, 
      dataType:'JSON', 
      success:function(data1){ 
      //clear the current content of the select 
      $select.empty(); 
      $select.append('<option value="-1">Select term </option>'); 
      //iterate over the data and append a select option 

      $.each(data1, function(key, val){ 
       $select.append('<option value="' + val.id + '">' + val.as_char + '</option>'); 
      }) 
      }, 

     }); 

} 

這是控制

<select class="select" id="id_leaseterm" name="leaseterm"> 
<option value="-1" selected="selected">-----</option> 
</select> 

它所有的作品,我改變我的下拉菜單和其他下拉菜單選項的值是updated.So我可以選擇相關的值。

問題是當我保存 - 爲表單獲取的值不是我放在那裏的值,而是在對Ajax進行任何操作之前已經存在的值。

另外,當我查看源代碼時,我在代碼中看到的是默認值,而不是從我用AJAX構建的東西中選擇的東西(即使在屏幕上,我也看到了選擇選項中的正確值... )

我的後端是Django。 我的Django表單格式如下。

class MassPaymentForm(forms.ModelForm): 

    leaseterm = forms.ModelChoiceField(queryset=LeaseTerm.objects.none()) # Need to populate this using jquery 
    lease= forms.ModelChoiceField(queryset=Lease.objects.none()) # Need to populate this using jquery 
    class Meta: 
     model = LeasePayment 

     fields = ['lease', 'leaseterm', 'payment_type', 'is_deposit', 'amount', 'method', 'payment_date', 'description'] 

可能是什麼問題?任何想法如何解決它?

+1

請檢查您的網頁的HTML源代碼(在瀏覽器中),並確保你只有一個''