Javascript DjangoAjax在for循环中不显示任何内容
我必须在ajax请求中使用for循环,我使用django inlineformset,当管理员选择一个项目时,它必须返回价格,但它在for循环中不起作用Javascript DjangoAjax在for循环中不显示任何内容,javascript,django,ajax,Javascript,Django,Ajax,我必须在ajax请求中使用for循环,我使用django inlineformset,当管理员选择一个项目时,它必须返回价格,但它在for循环中不起作用 class Item(models.Model): items = models.CharField(max_length=50) price = models.DecimalField(max_digits=10,decimal_places=3)#i have to return this price def
class Item(models.Model):
items = models.CharField(max_length=50)
price = models.DecimalField(max_digits=10,decimal_places=3)#i have to return this price
def __str__(self):
return self.items
class Invoice(models.Model):
admin = models.ForeignKey(User,on_delete=models.CASCADE)
customer = models.CharField(max_length=50)
items = models.ManyToManyField(Item,through='ItemsInvoice')
class ItemsInvoice(models.Model):
invoice_no = models.ForeignKey(Invoice,on_delete=models.CASCADE)
item = models.ForeignKey(Item,on_delete=models.CASCADE)
quantity = models.IntegerField()
price = models.DecimalField(max_digits=10,decimal_places=3)#when selecting an item , the price return back and write in the price field
我的观点
@login_required
def check_price(request):
item = request.GET.get('invoice-0-item',None)
price = Item.objects.get(id=item).price
print(price)
data = {
'price':price,
}
return JsonResponse(data)
我不知道如何通过迭代的形式来实现这一点
@login_required
def check_price(request):
for i in range(length of forms):
item = request.GET.get('invoice-'+i+'-item',None)
#etc
{%csrf\u令牌%}
{{items.management_form}
客户名称:
{form.customer | add_class:'bg-transparent w-full text center focus:outline none customer'}
{%if form.customer.errors%}
{{form.customer.errors}
{%endif%}
项目
量
价格
{items.forms%中的项的%s}
{{item.id}
{{item.item | add_class:'w-full item rounded lg text center focus:outline none py-1'}
{%if item.item.errors%}
{{item.item.errors}
{%endif%}
{{item.quantity | add_class:'rounded-lg dana文本中心焦点:outline none py-1 w-full'}
{%if item.quantity.errors%}
{{item.quantity.errors}
{%endif%}
{{item.price | add_class:'rounded-lg price text center focus:outline none py-1 w-full'}
{%if item.price.errors%}
{{item.price.errors}
{%endif%}
{%endfor%}
提交
函数sellingPrice(){
让inp=document.querySelectorAll(“.dynamic form>.inp”);
对于(让i=0;i经过一些讨论,您的问题现在清楚了。您必须使用jQuery事件作为select标记
将脚本更改为:
$('.inp select.item').change(function() {
let elm = $(this);
$.ajax({
url:'/ajax/price_validate/',
data:{
// elm.attr("name"): elm.val()
// OR keep it simple
"item_id": elm.val()
},
success:function(data){
if (data.price){
elm.closest("div.inp").find("input.price").val(data.price);
}
else{
alert('price doesn't provided')
}
}
})
})
views.py:
@login_required
def check_price(request):
query = request.GET
data = {
'price': Item.objects.get(id=query.get("item_id")).price,
}
return JsonResponse(data)
它返回500(内部服务器错误),不返回work@HunarMohammed,请分享您的回溯。什么错误?@Hunarmohamed,我编辑了我的答案。@Hunarmohamed,我用不同的方法编辑了我的答案。让我们来看看。