在Flask+DataTables表格中添加编辑/删除按钮的实现方法
给服务端渲染的DataTables添加编辑/删除按钮
1. 后端确保返回记录ID
首先要让每条食谱数据包含唯一ID,这样前端才能定位要编辑/删除的记录。修改Recipe模型的to_dict()方法,加入id字段:
def to_dict(self): return { 'id': self.id, 'name': self.name, 'ingredients_str': self.ingredients_str, 'cook_time': self.cook_time }
这样/api/data接口返回的每条数据都会带上id,供后续操作使用。
2. 前端添加操作列并渲染按钮
修改server_table.html中的DataTables配置,新增一列用来渲染编辑和删除按钮,同时绑定点击事件:
{% block scripts %} <script> $(document).ready(function () { $('#data').DataTable({ ajax: '/api/data', serverSide: true, columns: [ {data: 'name'}, {data: 'ingredients_str', orderable: false}, {data: 'cook_time', orderable: false}, { data: 'id', orderable: false, render: function(data, type, row) { // 生成带Bootstrap样式的操作按钮 return ` <button class="btn btn-sm btn-primary edit-btn" data-id="${data}">编辑</button> <button class="btn btn-sm btn-danger delete-btn" data-id="${data}">删除</button> `; } } ], }); // 绑定编辑按钮跳转事件 $('#data').on('click', '.edit-btn', function() { const recipeId = $(this).data('id'); window.location.href = `/recipe/${recipeId}/edit`; }); // 绑定删除按钮确认与请求事件 $('#data').on('click', '.delete-btn', function() { const recipeId = $(this).data('id'); if (confirm('确定要删除该食谱吗?')) { fetch(`/recipe/${recipeId}/delete`, { method: 'POST', headers: { 'X-CSRFToken': '{{ csrf_token() }}' // 需确保已配置Flask-WTF的CSRF保护 } }).then(response => { if (response.ok) { $('#data').DataTable().ajax.reload(); // 删除成功后刷新表格 } else { alert('删除失败,请重试'); } }); } }); }); </script> {% endblock %}
注:如果未使用Bootstrap,可自行替换按钮样式;若未配置Flask-WTF,需确保后端路由关闭CSRF验证(不推荐)或自行处理令牌。
3. 后端添加编辑与删除路由
在server_table.py中新增处理编辑页面和删除操作的路由:
# 编辑页面(GET请求) @app.route('/recipe/<int:id>/edit') def edit_recipe(id): recipe = Recipe.query.get_or_404(id) # 此处可结合Flask-WTF表单,示例:form = RecipeForm(obj=recipe) return render_template('edit_recipe.html', recipe=recipe) # 删除操作(POST请求) @app.route('/recipe/<int:id>/delete', methods=['POST']) def delete_recipe(id): recipe = Recipe.query.get_or_404(id) db.session.delete(recipe) db.session.commit() return '', 204 # 返回无内容的成功响应
若偏好使用DELETE请求,可将路由的methods改为['DELETE'],同时前端fetch的method对应改为'DELETE'即可。
补充说明
- 确保
Recipe模型包含id字段(Flask-SQLAlchemy默认会自动生成主键id)。 - 编辑页面的模板
edit_recipe.html需自行实现,表单提交逻辑可参考Miguel教程中的表单处理方式,新增更新路由(如/recipe/<int:id>/update)完成数据修改。
内容的提问来源于stack exchange,提问作者AWhite
相关产品推荐
相关产品推荐

