Home > front end >  Django request.POST loop
Django request.POST loop

Time:11-12

How can I loop through the request data and post it as one line in to the database, user can submit multiple descriptions, lengths and so on, problem I have is in the DB its creating massive amounts of rows to get to the correct format of the last one A1 but the user could submit A1,1,1,1,1; A2,2,2,8,100 and so on as its a dynamic add form)

descriptions  = request.POST.getlist('description')
    lengths = request.POST.getlist('lengthx')
    widths = request.POST.getlist('widthx')
    depths = request.POST.getlist('depthx')
    quantitys = request.POST.getlist('qtyx')
    for description in descriptions:
        for lengt in lengths:
            for width in widths:
                for depth in depths:
                    for quantity in quantitys:
                        newquoteitem = QuoteItem.objects.create(  
                        qdescription=description,
                        qlength=lengt,
                        qwidth=width,
                        qdepth=depth,
                        qquantity=quantity,
                        quote_number=quotenumber,
                        )

bottom entry is correct

post system

CodePudding user response:

First solutions
Use formsets. That is exactly what they are meant to handle.

Second solution
descriptions = request.POST.getlist('description') is returning a list of all descriptions, so let's say there are 5, it iterates 5 times. Now lengths = request.POST.getlist('lengthx') is a list of all lengths, again, 5 of them, so it will iterate 5 times, and since it is nested within the descriptions for loop, that's 25 times!

So, although I still think formsets are the way to go, you can try the following:

descriptions = request.POST.getlist('description')
lengths = request.POST.getlist('lengthx')
widths = request.POST.getlist('widthx')
depths = request.POST.getlist('depthx')
quantitys = request.POST.getlist('qtyx')

for i in range(len(descriptions)):
    newquoteitem = QuoteItem.objects.create(  
        qdescription=descriptions[i],
        qlength=lengths[i],
        qwidth=widths[i],
        qdepth=depths[i],
        qquantity=quantitys[i],
        quote_number=quotenumber,
    )

Here, if there are 5 descriptions, then len(descriptions) will be 5, and there is one loop, which will iterate 5 times in total.

  • Related