我使用Django 2.1和Python 3.7。我在一个表中有一些数据:
<table class="table" border="1" id="tbl_posts">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody id="tbl_posts_body">
<tr id="rec-1">
<td><span class="sn">1</span>.</td>
<td><INPUT type="text" name="txt1" value="Name"/></td>
<td><INPUT type="text" name="txt2" value="0"/></td>
<td><a class="btn btn-xs delete-record" data-id="1"><i class="glyphicon glyphicon-trash"></i></a></td>
</tr>
</tbody>
</table>用户可以编辑它,并且必须将其保存到Django中的数据库中。我该怎么做呢?我是Django的初学者。我可以使用表单或ajax或任何其他建议来实现吗?但我想保留这个结构。
发布于 2019-09-14 01:46:50
你可以做一个表单或者ajax。只要数据量相对较小(此表单就是如此),我就想不出使用<form>上传数据有什么坏处。
The Template
<form method="post">
{% csrf_token %}
<table class="table" border="1" id="tbl_posts">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody id="tbl_posts_body">
<tr id="rec-1">
<td><span class="sn">1</span>.</td>
<td><INPUT type="text" name="txt1" value="{{ txt1}}"/></td>
<td><INPUT type="text" name="txt2" value="{{ txt2}}"/></td>
<td><a class="btn btn-xs delete-record" data-id="1"><i class="glyphicon glyphicon-trash"></i></a></td>
</tr>
</tbody>
</table>
<input type="submit" value="Submit">
</form>查看的
def limitless(request):
template = "limitless.html"
context = {'txt1': "Name", 'txt2': 0}
if request.method == 'POST':
txt1 = request.POST.get("txt1")
txt2 = request.POST.get("txt2")
print(txt1 + " " + txt2)
#code to add variables to your models can go here
context = {'txt1' : txt1, 'txt2': txt2}
return render(request, template, context)发布于 2019-09-14 01:44:05
你可以像这样制作你的表单:
<form action="" method="post">
{% csrf_token %}
<table class="table" border="1" id="tbl_posts">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody id="tbl_posts_body">
<tr id="rec-1">
<td><span class="sn">1</span>.</td>
<td><input type="text" id="id_txt1" name="txt1" value="Name"></td>
<td><input type="text" id="id_txt2" name="txt2" value="0"></td>
<td><a class="btn btn-xs delete-record" data-id="1"><i class="glyphicon glyphicon-trash"></i></a></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"></td>
</tr>
</tbody>
</table>
</form>请注意,标记的name属性的值必须与您的模型中定义的字段名的值相同。
https://stackoverflow.com/questions/57927485
复制相似问题