After converting the Django models into a JSON data object and attempting to access it in Javascript, I ran into an issue. Specifically, I am unable to retrieve a field from the object and assign it to a text box.
The JSON
object that is returned appears as follows:
[{"model": "inventory.inventory","pk": 1, "fields":
{"product": "nice", "title": "Asus", "amount": 56000}},
{"model": "inventory.inventory", "pk": 2, "fields":
{"product": "nice", "title": "Lenovo", "amount": 55000}}]
Here is the snippet of javascript code that I am currently using:
<html>....{{ data|json_script:"hello-data" }}....
<script type="text/javascript">
const data = JSON.parse(document.getElementById('hello-data').textContent);
document.getElementById('id_line_one').onchange = function(){
var line_one=document.getElementById('id_line_one').value;
var id=line_one-1;
document.getElementById('id_line_one_unit_price').value = data[id].fields.amount;
};
</script>....</html>
https://i.sstatic.net/g8dFv.jpg
When selecting a title from the dropdown list, the return value is its primary key, known as product_number
. My objective is to fetch the associated amount
for that particular product based on the selected product_number
.
Given that objects in JSON are indexed starting from 0(?), I initially believed my code logic was accurate. However, lacking expertise in this area, I suspect I may have overlooked a simple mistake.
Any suggestions on how I can display the amount of the object in the unit price
text box upon selecting a title from the dropdown list would be greatly appreciated.
Thank you!
views.py
@login_required
def add_invoice(request):
form = InvoiceForm(request.POST or None)
data = serializers.serialize("json", Inventory.objects.all())
total_invoices = Invoice.objects.count()
queryset = Invoice.objects.order_by('-invoice_date')[:6]
if form.is_valid():
form.save()
messages.success(request, 'Successfully Saved')
return redirect('/invoice/list_invoice')
context = {
"form": form,
"title": "New Invoice",
"total_invoices": total_invoices,
"queryset": queryset,
"data": data,
}
return render(request, "entry.html", context)