Accessing values in a JSON array and then assigning it to a textfield

Viewed 55

My question is very simple. By using the DjangoJSONEncoder, I am able to send a JSON array of Model instances with the fields, product_number(pk) and amount as context to the HTML file. I then access the JSON array obj using some javascript code.

The JS code:

{{ 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(event){
            alert(data);
            document.getElementById('id_line_one_unit_price').value = data[event.target.value].value
};

</script>

The array is:

[[1, 56000], [2, 55000]]

I think it's a string and not an array? I have a dropdown box and when the user selects a title from the dropdown menu, It returns the primary key of that title, and then using that, I want to retrieve the amount of that product from the JSON array and then set the value of a text field with that amount. ss

views.py:

def add_invoice(request):
  form = InvoiceForm(request.POST or None)
  total_invoices = Invoice.objects.count()
  queryset = Invoice.objects.order_by('-invoice_date')[:6]

  dataa = Inventory.objects.values_list('product_number','amount')
  data = json.dumps(list(dataa), cls=DjangoJSONEncoder)

  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)

models.py:

from django.db import models

class Inventory(models.Model):
  product_number = models.IntegerField(primary_key=True)
  product = models.TextField(max_length=3000, default='', blank=True, null=True)
  title = models.CharField('Title', max_length=120, default='', blank=True, unique=True)
  amount = models.IntegerField('Unit Price', default=0, blank=True, null=True)

  def __str__(self):
    return self.title

I noticed that the javascript code is actually working correctly, It sends the ith element, i.e., if the title selected has a primary key 1 then [ is returned as result and if the primary key is 2, the output is 1. The array or string(?) is [[1, 56000], [2, 55000]] So it's basically treating the variable data as a string. I want it to be a dictionary? How can I convert this string I am getting into a dictionary and then map the result of the amount to its text fields?

Thanks.

0 Answers
Related