在django中,我能够通过js创建添加和删除行。如何将这些数据行添加到Django DB中。 它仅保存最后一行条目。这是以下代码。
查看:
def dynamicRow(request, *args, **kwargs):
form = Add_Form(request.POST or None)
template_name = 'addentry.html'
if request.method == 'POST':
if form.is_valid():
no_of_rows = int(request.POST.get('totalnum'))
print(no_of_rows)
list_of_rows = [Add_Form() for i in range(no_of_rows)]
args = {'forms': list_of_rows}
for i in args['forms']:
print(i) ## only prints last entry
i = Add_Form(request.POST)
task = i.save(commit=False)
task.save()
messages.success(request, 'Successfully stored data into database.')
else:
messages.error(request, form.errors)
else:
form = Add_Form()
return render(request, template_name, {'form': form })
HTML:
<form id="add_data" role=form method="POST" class="post-form" action="">{% csrf_token %}
<div class="container">
<table id="table" class=" table order-list">
<thead class="thead-light">
<tr>
<th scope="col">Device#</th>
<th scope="col">Name</th>
</tr>
</thead>
<tbody>
<tr>
<td class="col-sm-4">
<input type="mail" name="device" class="form-check"/>
</td>
<td class="col-sm-4">
<input type="mail" name="name" class="form-check"/>
</td>
<td class="col-sm-2"><a class="deleteRow"></a>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" />
</td>
</tr>
</tfoot>
</table>
<div class="row">
<div align="center" class="col">
<h4>Number of Rows: </h4>
<input name="totalnum" id="totalnum" class="form-control" type="text" maxlength="2"></input>
</div></div>
</div> <!-- container -->
<br><br>
<div class="row "><div class="col">
<button type="submit" name="submit" class="btn">Submit</button><p><p>
</div></div>
</form>
<!-- SCRIPTS -->
使用add
和delete
按钮,我可以生成行。当我点击“提交”时,“仅接受”并从列表中添加到数据库中。
如果我有10行,那么如何在DB中一个接一个地动态创建条目。 谢谢您的帮助。