You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django框架下HTML表格可编辑notes字段更新后保存到数据库的实现问题

解决方案

核心问题对应解答

  1. 如何标识要更新的记录:把每条TM记录的主键ID存入页面元素的自定义属性,提交更新时和笔记内容一起传给后端,后端用ID查询对应记录再更新即可
  2. 保存后刷新:在AJAX请求的成功回调函数中调用window.location.reload()即可实现整页刷新,也可以选择局部更新DOM优化体验

现有代码问题修正

1. 修改detail.html模板

你当前所有笔记单元格共用同一个id=notes违反HTML规范(ID必须全局唯一),且没有传递记录标识,修改后代码如下:

<head>
    <!-- 新增CSRF Token的meta标签,供单独的JS文件读取 -->
    <meta name="csrf-token" content="{{ csrf_token }}">
</head>
<body>
<table class= "content-table">
    <thead>
        <tr>
            <th>Name</th>
            <th>Distributor</th>
            <th>State</th>
            <th>Brand</th>
            <th>Cell</th>
            <th>Email</th>
            <th>Notes</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        {% for tm in territory_manager %}
        <tr>
            <td style="white-space:nowrap;">{{ tm.Name }}</td>
            <td style="white-space:nowrap;">{{ tm.Distributor }}</td>
            <td style="white-space:nowrap;">{{ tm.State }}</td>
            <td style="white-space:nowrap;">{{ tm.Brand }}</td>
            <td style="white-space:nowrap;">{{ tm.Cell }}</td>
            <td style="white-space:nowrap;">{{ tm.Email }}</td>
            <!-- 用class标识笔记单元格,新增自定义属性存对应记录的ID -->
            <td class="notes-cell" contenteditable="True" data-tm-id="{{ tm.id }}">{{ tm.Notes }}</td>
            <!-- 按钮也绑定对应记录ID,改成button类型避免默认表单提交 -->
            <td><input type='button' align="right" value='Update' class='btn btn-primary update-note-btn' data-tm-id="{{ tm.id }}"></td>
        </tr>
        {% endfor %}
        {% else %}
        <tr><td colspan="8"><h2>No Results for: {{ state }} </h2></td></tr>
        {% endif %}
    </tbody>
</table>
<script src="assets/js/notes.js"></script>        
</body>

2. 修改notes.js代码

你之前的AJAX地址写的是本地文件路径是错误的,需要走Django的路由地址,同时绑定按钮点击事件获取对应行数据:

$(document).ready(function() {
    // 给所有更新按钮绑定点击事件
    $('.update-note-btn').click(function() {
        // 读取当前按钮对应的记录ID
        const tmId = $(this).data('tm-id');
        // 读取对应行的笔记内容
        const noteContent = $(`.notes-cell[data-tm-id="${tmId}"]`).text();
        // 读取CSRF Token
        const csrfToken = $('meta[name="csrf-token"]').attr('content');

        $.ajax({
            type: 'POST',
            // 这里填后面你在urls.py里配置的路由地址
            url: '/api/update-note/',
            data: {
                tm_id: tmId,
                note: noteContent,
                csrfmiddlewaretoken: csrfToken
            },
            success: function(res) {
                alert('保存成功');
                // 保存成功后刷新页面
                window.location.reload();
            },
            error: function(err) {
                console.error('保存失败', err);
                alert('保存失败,请重试');
            }
        })
    })
})

3. 配置Django路由

在你app的urls.py中新增更新接口的路由映射:

from django.urls import path
from . import views

urlpatterns = [
    # 你原有其他路由保留,新增下面这条
    path('api/update-note/', views.notes, name='update_note'),
]

4. 修改views.py代码

你之前的写法会全表更新所有TM记录的笔记,必须先查单条记录再更新,AJAX请求不需要返回整个页面,返回JSON即可:

from django.http import JsonResponse

def notes(request):
    if request.method == 'POST' and request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest':
        tm_id = request.POST.get('tm_id')
        note_content = request.POST.get('note')
        try:
            # 查询对应记录再更新
            tm_obj = TM.objects.get(id=tm_id)
            tm_obj.Notes = note_content
            tm_obj.save()
            return JsonResponse({'code': 0, 'msg': '更新成功'})
        except TM.DoesNotExist:
            return JsonResponse({'code': 1, 'msg': '记录不存在'}, status=404)
    return JsonResponse({'code': 2, 'msg': '非法请求'}, status=400)

内容的提问来源于stack exchange,提问作者Justin Benfit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 04:27:02