我正在尝试使用Ajax调用从CreateView的下拉列表中检索所选项目的值。例如,当从下拉菜单中选择一个项目时,我希望该项目的所有相关信息自动显示在模板上。
但是我不确定为什么我无法使用以下代码在CreateView中返回所选项目的值(过滤所需的值):
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)
<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>
$(document).ready(function(){
$("#id_item").change(function(){
var item_selection = $(this).val();
$.ajax({
type: "GET",
data: {"item_name_id": item_selection}
});
});
});
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上可用的功能之一。
有人对此有解决方案吗?