2017-09-24 46 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源代码(在浏览器中),并确保你只有一个''