I converted the Django models into a JSON data object and accessed it in Javascript. However, I cannot access a field from the object and assign it to a text box.
The JSON
object that is being returned:
[{"model": "inventory.inventory","pk": 1, "fields":
{"product": "nice", "title": "Asus", "amount": 56000}},
{"model": "inventory.inventory", "pk": 2, "fields":
{"product": "nice", "title": "Lenovo", "amount": 55000}}]
The javascript code that I am 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>
The dropdown value returns its primary key, i.e., product_number
and basically I want to fetch the amount
of the product associated with that product_number
.
As the objects are stored from 0(?) in JSON, I thought the logic of my code was correct but I am not an expert so I am pretty sure I am making some silly mistake here.
How can I return the amount of the object in the unit price
text box when the title is selected in the dropdown list?
Thanks!
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)
CodePudding user response:
in your case is better to use array.find()
document.getElementById('id_line_one').onchange = function(event){
let elementInData = data.find((item) => item.pk == event.target.value);
document.getElementById('id_line_one_unit_price').value = elementInData && elementInData.amount ? elementInData.amount : 0;
};
but you can create your data as dictionary:
data = serializers.serialize("json", Inventory.objects.in_bulk())
after that you should see in javascript:
data = JSON.parse(document.getElementById('hello-data').textContent);
// data is {1: {"model": "inventory.inventory","pk": 1, "fields":
{"product": "nice", "title": "Asus", "amount": 56000}}, ...}
after that you can achieve every element by key:
document.getElementById('id_line_one_unit_price').value = data[event.target.value].fields.amount
without arr.find().