[英]Django forms: how to get product's data from db with ajax
我有模型(ShopStock 和 SaleItem),我在 ShopStock 模型中注册了产品和价格,在 SaleItem 模型中我也有产品和价格字段。 我想要的是当我在 (SaleItemForm) 中选择要填充 Shopstock 模型价格的价格字段中的产品时。 我不知道如何在 javascript 中做到这一点。
楷模
class Product(models.Model):
name = models.CharField(max_length = 100, blank=True)
class ShopStock(models.Model):
products = models.ForeignKey(Product, null=True, blank=True, on_delete = models.SET_NULL)
price = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True)
class SaleItem(models.Model):
product = models.ForeignKey(ShopStock, null=True, blank=True, on_delete = models.SET_NULL)
quantity = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True)
price = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True)
我试过这个来解决我的问题,但它不起作用
观看次数
def price(request):
if request.method == 'GET':
total_price = SaleItem.price
response_data ={}
response_data['price'] = total_price
return JsonResponse(response_data)
模板
$(document).ready(function() {
$('#id_product').change(function(){
var query = $(this).val();
console.log(query);
$.ajax({
url : "/price/",
type : "GET",
dataType: "json",
data : {
client_response : query
},
success: function(json) {
document.getElementById('id_price').value=json.price;
},
failure: function(json) {
alert('Got an error dude');
}
});
});
});
形式
class SaleItemForm(forms.ModelForm):
product = forms.ModelChoiceField(queryset=ShopStock.objects.all(), widget=forms.Select(attrs={'class':'form-control', 'id':'id_product'}))
class Meta:
model = SaleItem
fields = ['product', 'quantity', 'price']
widgets = {
'quantity': forms.NumberInput(attrs={'class': 'form-control'}),
'price': forms.NumberInput(attrs={'class': 'form-control', 'id':'id_price'})
}
网址
url(r'^price/$', views.price, name='price')
任何帮助或想法将不胜感激。
问题在于total_price = SaleItem.price
。 哪个 SaleItem 实例的价格? 您需要过滤并获取特殊模型实例。
您已经通过data :{client_response : query}
将数据从 ajax 函数传递到视图。 因此,您可以使用它来过滤 .
def price(request):
if request.method == 'GET':
selectedProduct = request.GET['client_response']
total_price = SaleItem.objects.filter(product = selectedProduct).first().price
response_data ={}
response_data['price'] = total_price
return JsonResponse(response_data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.