我试图使用Ajax调用从CreateView的下拉列表中检索所选项的值 . 例如,当从下拉菜单中选择一个项目时,我希望该项目的所有相关信息自动显示在模板上 .
但我不知道为什么我无法使用以下代码返回CreateView中所选项目(过滤所需的值)的值:
models.py
class Model_Item(models.Model):
item_name = models.CharField(max_length = 20)
item_description = models.CharField(max_length = 100)
item_origin = models.CharField(max_length = 50)
# and many more fields
def __unicode__(self):
return self.item_name
class Model_Cart(models.Model):
item = models.ForeignKey(Model_Item)
customer_name = models.CharField(max_length = 50)
html
<form method = "POST"> {% csrf_token %}
<table id = "table_01">
<tr>
<th>Item name</th>
<td>{{ form.item}}</td>
</tr>
</table>
<div>
preview the description, origin and other fields of the choosen item here -->
</div>
<table id = "table_02">
<tr>
<th>Customer's name</th>
<td>{{ form.customer_name}}</td>
</tr>
</table>
<input type = "submit" value = "Submit">
</form>
ajax
$(document).ready(function(){
$("#id_item").change(function(){
var item_selection = $(this).val();
$.ajax({
type: "GET",
data: {"item_name_id": item_selection}
});
});
});
views.py
class View_Cart(CreateView):
form_class = Form_Cart
def get_queryset(self):
item_name_id = self.request.GET.get("item_name_id")
print item_name_id # <------ Does not print anything
我提到this link但无济于事 . This source说我们不能在CreateView上使用"get_queryset",但是here它说"get_queryset"是CreateView上可用的函数之一 .
有没有人有解决方案?