尝试使用django表单保存时,动态构建AJAX下拉列表重置为原始状态?

我的forms我用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('Select term '); //iterate over the data and append a select option $.each(data1, function(key, val){ $select.append('' + val.as_char + ''); }) }, }); } 

这就是控制

  -----  

一切正常,我在下拉列表中更改值,并更新其他下拉列表的选项。所以我可以选择相关值。

问题是当我保存for时 – 表单不是我放在那里的值,而是在完成任何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'] 

可能是什么问题呢 ? 任何想法如何解决它?

我已经弄清楚它在我的表单文件中是什么问题

如果我在Meta类中保留lease和leaseterm字段,它不再重置那些字段。 而我的所有逻辑终于按设计工作了。

 class MassPaymentForm(forms.ModelForm): class Meta: model = LeasePayment fields = ['lease', 'leaseterm', 'payment_type', 'is_deposit', 'amount', 'method', 'payment_date', 'description']