[英]How to insert multiple rows of data from dynamically generated rows into a database using Python Django
我有一个 Javascript function (addItem),它允许用户添加任意数量的动态生成的数据行并填写所需的必要字段。 请参阅下面的代码
<div class="modal-body">
<table class="table order-list table-striped" id="myTable">
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody id="addItems">
</tbody>
</table>
<table>
<tbody>
<tr>
<td colspan="5" style="text-align: left;">
<button onclick="addItem();" class="btn btn-sm btn-success" id="sspusd1" value="Add Row"><i class="fa fa-plus"></i>Add Row</button>
</td>
<td colspan="5" style="text-align: left;">
</td>
</tr>
</tbody>
</table>
</div>
function addItem() {
renumber++;
var html = "<tr>";
html += "<td><select class='form-control'>{% for stock in stocks %}<option class='dropdown-item' value='{{stock.inventoryPart}}'>{{stock.inventoryPart}}</option>{% endfor %}</select></td>";
html += "<td><input type='number' class='form-control' onblur='lineTotal(this);' value='0' name='quantity[]'/></td>";
html += "<td><input type='text' class='form-control' onblur='lineTotal(this);' value='0' name='price[]'/></td>";
html += "<td><input type='text' id='lineTotal' class='form-control' value='0' disabled name='total[]' /></td>";
html += "</tr>";
document.getElementById("addItems").insertRow().innerHTML = html;
};
但是,One 能够插入他们想要的任意数量的行,并将必要的数据插入到可用的字段中。
问题是我无法捕获和存储输入到这些动态行中的动态信息,因为 Django 不知道用户创建了多少行。
目的是能够使用 Django 将用户插入的创建的动态行中的数据存储到数据库中
以下是我认为的代码
def customers(request):
if request.method == 'POST':
if 'Receipttotal' in request.POST:
stocksArr = request.POST.getlist('stock')
quantityArr = request.POST.getlist('quantity')
priceArr = request.POST.getlist('price')
totalArr = request.POST.getlist('total')
print("---Array Data---")
print(stocksArr)
print(quantityArr)
print(priceArr)
print(totalArr)
所以打印语句 output 是一个空列表。
这个功能怎么可能? 我需要这方面的帮助。 谢谢。
我看到的最好的解决方案是使用带有 HTMX 的表单集。 你可以按照这个优秀的教程https://justdjango.com/blog/dynamic-forms-in-django-htmx
我想你在 html 的某个地方有这样的表格:
<form action="" method="post">
<!-- Your table etc. here -->
</form>
在这种情况下,请尝试以这种方式修改您的视图:
if request.method == 'POST':
stocksArr = request.POST.getlist('stock')
quantityArr = request.POST.getlist('quantity')
priceArr = request.POST.getlist('price')
totalArr = request.POST.getlist('total')
print("---Array Data---")
print(stocksArr)
print(quantityArr)
print(priceArr)
print(totalArr)
现在,您的表单可能没有if 'Receipttotal' in request.POST:
。 试试这种方式,让我知道这是否能解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.