Django-Bootstrap表格内联编辑:实现可编辑评论列的保存功能
实现可编辑评论列并保存数据的方案
1. 后端视图(以Django为例)
在views.py中新增处理评论更新的视图,接收POST请求修改对应数据的editablecomments字段:
from django.http import JsonResponse from .models import YourModel # 替换为你的实际模型类 from django.views.decorators.csrf import csrf_exempt @csrf_exempt # 若项目启用CSRF令牌,可移除该装饰器并在前端携带令牌 def update_comment(request): if request.method == 'POST': data_id = request.POST.get('id') new_comment = request.POST.get('comment') try: instance = YourModel.objects.get(id=data_id) instance.editablecomments = new_comment instance.save() return JsonResponse({'status': 'success'}) except YourModel.DoesNotExist: return JsonResponse({'status': 'error', 'message': '数据不存在'}) return JsonResponse({'status': 'error', 'message': '仅支持POST请求'})
同时在urls.py中添加对应路由:
from django.urls import path from . import views urlpatterns = [ # 其他已有路由 path('update-comment/', views.update_comment, name='update_comment'), ]
2. 前端模板修改
给可编辑的<td>添加数据标识,方便JS定位对应记录:
<tbody> {% for a in data %} <tr> <td><a id="idclicked" href="datadescription/{{a.id}}/" title="click to see Metadata" style="color: rgb(30, 61, 199); font-weight:bold;"><u>{{ a.id }}</u></a></td> <td>{{ a.Date }}</td> <td>{{ a.Name }}</td> <td>{{ a.Affliations}}</td> <td>{{ a.Methods}}</td> <td>{{ a.Instruments}}</td> <td>{{ a.device}}</td> <td>{{ a.comments }}</td> <!-- 添加data-id属性绑定当前数据ID --> <td contenteditable="true" data-id="{{a.id}}">{{ a.editablecomments }}</td> </tr> {% endfor %} </tbody>
3. 前端JavaScript逻辑
监听编辑完成事件(失去焦点或回车),将修改内容提交到后端:
// 监听所有可编辑td元素 document.querySelectorAll('td[contenteditable="true"]').forEach(td => { // 失去焦点时提交 td.addEventListener('blur', function() { const dataId = this.getAttribute('data-id'); const newComment = this.textContent.trim(); fetch('/update-comment/', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `id=${dataId}&comment=${encodeURIComponent(newComment)}` }) .then(response => response.json()) .then(result => { if (result.status === 'error') { console.error('保存失败:', result.message); } }) .catch(error => { console.error('请求出错:', error); }); }); // 可选:按下回车时提交并阻止换行 td.addEventListener('keydown', function(e) { if (e.key === 'Enter') { e.preventDefault(); this.blur(); // 触发blur事件提交 } }); });
注意事项
- 若项目启用CSRF保护,需在请求中携带CSRF令牌,可通过Django的
{% csrf_token %}获取并添加到请求头或表单中。 - 可根据需求调整提交触发时机(如定时保存、添加保存按钮等)。
- 可添加加载状态提示,避免用户重复提交,提升体验。
内容的提问来源于stack exchange,提问作者user11603936
相关产品推荐
相关产品推荐

