How can insert list items to database in django?

Viewed 362

Here is my template :

{% for pr in productlist %}

<ul>
  <li>{{ pr.productid }} <input type="hidden" id="prid" name="mylist" value="{{ pr.productid }} "></li>
  <li>{{ pr.productname }} <input type="hidden" id="prname" name="mylist" value="{{ pr.productname }}"></li>
  <li><input type="number" name="mylist" id="prqty"/></li>
</ul>

{% endfor %}

I get list of items in view : pd = request.POST.getlist("mylist") and result is:

 1
 product1
 23

 2
 product2
 44

 3
 product3
 18

and complete view is this :

def post(self, request):
    if request.user.is_authenticated:
        
        pd = request.POST.getlist("mylist")  
        
        #invoice
        invoice = models.Sellinvoice.objects.create(                    
                type = "5",
                date = datetime.datetime.now()
                )
        
        #invoiceItems
        for item in pd:
                qty = 1
                models.Sellinvoiceitems (
                                productid = <<-- problem,
                                productname = <<-- problem,
                                totalnumber = <<-- problem,
                                sellinvoice = invoice,
                                stockid = stock
                            ).save()

                invoice.save()

My question is how i save all item in above list using for each?

1 Answers

You can enumerate over chunks of three with:

pd = request.POST.getlist('mylist') 
pdi = iter(pd)
for pid, pname, ptotal, __ in zip(pdi, pdi, pdi, pdi):
    models.Sellinvoiceitems.objects.create(
        productid=pid
        productname=pname,
        totalnumber=ptotal,
        sellinvoice = invoice,
        stockid = stock
    )

That being said, I would advise not to process POST parameters yourself. You can work with a FormSet for that [Django-doc].

Related