我有一个表格,你点击它会得到列和单元格的值,例如:
{"name" : Clark}
现在如何将输出直接放入表单并保存到数据库中,只需单击同一个表格单元格而不需要按钮或显示字段。HTML 中的字段仅用于测试,稍后会将其隐藏。
非常感谢任何帮助
这是我的代码
模型.py
class OnClickFormSave(models.Model):
data = models.CharField(max_length=100)
def __str__(self):
return self.data
表单.py
class OnClickFormSaveForm(forms.ModelForm):
class Meta:
model = OnClickFormSave
fields = ['data']
查看.py
def formsave_view(request):
form = OnClickFormSaveForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
return HttpResponseRedirect('/form')
return render(request, 'onClickSave.html', {'form': form})
HTML
<form method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form.data }}
<input type="submit" value="Save Changes" />
</form>
<table align="center" id="tableID" border="1" style="cursor: pointer;">
<thead>
<tr>
<th id="name">name</th>
<th id="age">age</th>
<th id="ID">ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>Clark</td>
<td>29</td>
<td>1</td>
</tr>
<tr>
<td >Bruce</td>
<td>30</td>
<td>2</td>
</tr>
</tbody>
</table>
Javascript
$('table tbody tr td').on("click", getColumnID);
function getColumnID() {
var $td = $(this),
$th = $td.closest('table').find('th').eq($td.index());
var head = $th.attr("id");
$row = ($(this).text());
var table = $row;
var cell = `{"${head}" : ${table}}`;
console.log(cell);
}
您可以将网址与数据一起调用!POST 方法已经足够好了。在jQuery.post 中,您已经拥有单元格变量中的数据。
// before that you need to change the dict to `{'data': value}` so django will pick up this...
$.post( "/formsave-view", cell)
.done(function( data ) {
console.log(data);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句