I want to convert the model instances into a JSON object and then pass it 
to the HTML file. However, I get an AttributeError at this line:
`data = serializers.serialize("json", Inventory.objects.in_bulk())`

The full `views.py`:

    def add_invoice(request):
      form = InvoiceForm(request.POST or None)
      data = serializers.serialize("json", Inventory.objects.in_bulk())
      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)

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

    </script>

`models.py`:

    

    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

How can I pass that JSON object and assign the amount value to the text 
field according to the object selected in the dropdown? Thanks
[image: Screenshot 2022-07-09 232808.jpg]

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/6176f7fe-9f50-4380-b044-3e46f2219c8fn%40googlegroups.com.

Reply via email to