基于Django实现Datatable表格状态保存与加载的问题求助
核心问题修复说明
以下是你代码中存在的问题及修正后的可运行代码:
- 前端
stateLoadCallback未调用Datatables要求的callback方法传递状态数据,还存在未定义变量、语法错误的问题 - 后端GET接口返回列表结构而非单个状态对象,存储时未将JSON对象转字符串、读取时未转回JSON,且查询/更新状态未过滤当前用户,会导致多用户状态串扰
- 模型字段选型不合理,
CharField长度容易溢出
修正后前端Datatable初始化代码
var tableSumm = $('#summary_table').DataTable({ stateSave: true, stateSaveCallback: function (settings, data) { const tableId = $(this).attr("id"); const URL = window.location.origin + '/api/state/' + tableId + '/'; fetch(URL, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': csrftoken }, body: JSON.stringify(data) }); }, stateLoadCallback: function (settings, callback) { const tableId = $(this).attr("id"); const URL = window.location.origin + '/api/state/' + tableId + '/'; fetch(URL, { headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' } }) .then(response => response.json()) .then(stateData => { // 调用callback将状态传递给Datatable完成渲染 callback(stateData); }); } });
修正后TableState模型代码
from django.db import models from django.contrib.auth.models import User import json class TableState(models.Model): """ 存储用户的表格状态 """ user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) tablename = models.CharField('表名', max_length=50, null=True) # 改用TextField存储更长的JSON内容,避免长度溢出 columnsdata = models.TextField('列状态数据', null=True) # 新增属性方法,直接返回JSON格式的状态数据 @property def state_data(self): if self.columnsdata: return json.loads(self.columnsdata) return None def __str__(self): return self.tablename class Meta: unique_together = ('user', 'tablename')
修正后Django视图代码
import json from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET', 'POST', 'DELETE']) def stateListDetail(request, table_name): # 先校验用户登录状态 if not request.user.is_authenticated: return Response(status=status.HTTP_401_UNAUTHORIZED) if request.method == 'GET': # 过滤当前用户+当前表名的唯一状态 state_obj = TableState.objects.filter(user=request.user, tablename=table_name).first() if not state_obj: return Response(status=status.HTTP_404_NOT_FOUND) # 直接返回JSON格式的状态数据 return Response(state_obj.state_data) elif request.method == 'POST': # 更新时过滤当前用户,避免覆盖其他用户的状态 state_obj = TableState.objects.filter(user=request.user, tablename=table_name).first() # 将前端传的JSON对象转成字符串存储 state_json = json.dumps(request.data) if state_obj: state_obj.columnsdata = state_json state_obj.save() else: TableState.objects.create( user=request.user, tablename=table_name, columnsdata=state_json ) return Response(status=status.HTTP_201_CREATED) elif request.method == 'DELETE': state_obj = TableState.objects.filter(user=request.user, tablename=table_name).first() if state_obj: state_obj.delete() return Response(status=status.HTTP_204_NO_CONTENT)
内容的提问来源于stack exchange,提问作者Ritesh
相关产品推荐
相关产品推荐

