Django无需跳转UpdateView页面直接调用实现列表内字段更新的方法咨询
Django 列表页行内直接编辑实现方案
1. 修改视图文件 views.py
给原有列表视图 MachineView 新增POST请求处理逻辑,接收行内提交的更新数据:
from django.shortcuts import redirect class MachineView(ListView): model = Machine fields = ['machine', 'currently_running'] template_name = 'viewer/machine_view.html' def post(self, request, *args, **kwargs): machine_id = request.POST.get('machine_id') # 只要请求里带了currently_running字段就处理,支持空值提交 if machine_id and 'currently_running' in request.POST: try: machine_obj = Machine.objects.get(id=machine_id) machine_obj.currently_running = request.POST.get('currently_running') machine_obj.save() except Machine.DoesNotExist: pass # 重定向回列表页刷新数据,redirect参数对应你urls.py中MachineView路由的name值 return redirect('machine_view') # 原有MachineUpdateView如果不需要可以直接删除
2. 修改列表模板 machine_view.html
将原有列表每行改为独立表单,内置编辑输入框和提交按钮:
<table> <thead> <tr> <th>设备名称</th> <th>当前运行任务</th> <th>操作</th> </tr> </thead> <tbody> {% for machine in object_list %} <tr> <td>{{ machine.machine }}</td> <!-- 每行独立表单,避免提交时数据互相干扰 --> <form method="post"> {% csrf_token %} <!-- 隐藏域传递当前行数据ID --> <input type="hidden" name="machine_id" value="{{ machine.id }}"> <td> <input type="text" name="currently_running" value="{{ machine.currently_running }}"> </td> <td><button type="submit">保存</button></td> </form> </tr> {% endfor %} </tbody> </table>
3. 路由配置说明
原有路由无需额外修改,只要确保 MachineView 对应的路由配置了正确的name,和视图中redirect的参数一致即可,示例urls.py配置参考:
from django.urls import path from . import views urlpatterns = [ path('machines/', views.MachineView.as_view(), name='machine_view'), # 原MachineUpdateView的路由如果不需要可以删除 ]
可选优化
如果不想刷新页面,可以加少量JS代码用AJAX提交表单,替换原有行内容即可,无需修改后端逻辑。
内容的提问来源于stack exchange,提问作者Josh_At_Sorenson
相关产品推荐
相关产品推荐

