我已經嘗試了所有可能的解決方案在幾個線程,我仍然無法解決問題。我有以下代碼:ModelChoiceField給出了「選擇一個有效的選擇」填充選擇與阿賈克斯呼籲
models.py
class CustomerVisit(models.Model):
start_date = models.DateField()
end_date = models.DateField()
customer = models.ForeignKey(Customer)
address = models.ForeignKey(Address)
forms.py
address = forms.ModelChoiceField(label='Address',
queryset=Address.objects.none(),
widget=forms.Select(attrs={'style': 'width: 100%;'}))
customer = forms.ModelChoiceField(label='Customer',
queryset=Customer.objects.all(),
widget=forms.Select(attrs={'style': 'width: 100%;'}))
views.py
if request.method == "POST":
# Cleaning fields
post = request.POST.copy()
post['address'] = Address.objects.get(id=post['address'])
post['start_date'] = dateparser.parse(post['start_date'])
post['end_date'] = dateparser.parse(post['end_date'])
# Updating request.POST
request.POST = post
form = CustomerVisitForm(request.POST)
if form.is_valid():
form.save(commit=True)
return redirect("customervisit:calendar")
個JS
$("#id_customer").select2({}).on("change", function() {
var customer_id = $("#id_customer").val();
var id_address = $("#id_address");
id_address.select2({
ajax: {
url: '/get_customer_address/' + customer_id,
dataType: "json",
type: "GET",
data: function (params) {
var queryParameters = {
term: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
}
});
});
我address
選擇基於使用ajax call using select2customer
選擇其被填充。閱讀幾個線程後,我注意到,modelchoicefield
期望一個Address
對象,這就是爲什麼我用我的看法如下代碼正在驗證之前的形式:post['address'] = Address.objects.get(id=post['address'])
但我仍然得到Select a valid choice. That choice is not one of the available choices.
錯誤
我使用queryset=Address.objects.none(),
因爲我需要一個空的選擇
你不應該這樣做。所有這些邏輯都應該以這種形式出現。 –
@DanielRoseman我相信你在談論清潔領域吧?如果是這樣,我有TODO來改變這一點。謝謝 –
但關鍵是你不想爲地址字段進行轉換。我不知道爲什麼你認爲它需要一個實例,表單字段的要點是他們需要POST數據並將其轉換爲適當的類型。 –