When using a for loop inside my ajax request with Django inlineformset, the goal is to return the price when an admin selects an item. However, this functionality is not working correctly within the for loop.
class Item(models.Model):
items = models.CharField(max_length=50)
price = models.DecimalField(max_digits=10, decimal_places=3) # I need to retrieve 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 should be returned and populated in the price field
Here's a snippet of my views.py:
@login_required
def check_price(request):
item = request.GET.get('invoice-0-item', None)
price = Item.objects.get(id=item).price
data = {
'price': price,
}
return JsonResponse(data)
I'm struggling with iterating through the number of forms to achieve this:
@login_required
def check_price(request):
for i in range(length of forms):
item = request.GET.get('invoice-' + str(i) + '-item', None)
# etc...
Lastly, I have to assign the returned price to the price field, but it fails within the for loop. Is there any way to accomplish this?
Updated: forms.py
class InvoiceItemForm(forms.ModelForm):
item = forms.ModelChoiceField(
queryset=Item.objects.all(), empty_label='---', widget=forms.Select(attrs={'onchange':'sellingPrice()'}))
class Meta:
model = ItemsInvoice
fields = [
'item', 'quantity', 'price'
]
class CustomerInvoiceForm(forms.ModelForm):
class Meta:
model = Invoice
fields = [
'customer'
]
CustomerInvoiceInlineFormset = inlineformset_factory(
Invoice, ItemsInvoice, form=InvoiceItemForm,
fields=('item', 'quantity', 'price'), extra=1
)