Shortlist与Reject按钮异常:仅最后一个生效且状态无法写入数据库
表格按钮仅最后一行生效且状态无法更新问题解决
问题现象
- 点击表格中任意行的Shortlist或Reject按钮时,仅最后一行的按钮能正常触发请求
- 控制台可打印点击的status值,但无法将该状态同步至数据库
问题原因
- 表单字段冲突:整个表格被包裹在单个
<form>标签内,循环生成的每一行都包含同名的Application_id隐藏字段和status提交按钮。表单提交时,浏览器只会发送最后一个同名字段的值,导致后端始终获取最后一行的Application_id,仅最后一行操作能匹配正确记录。 - 后端未执行更新操作:视图函数中仅获取了
status值,但未将该值赋值给Application对象的对应字段就直接调用save(),相当于未做任何数据更新,状态自然无法同步到数据库。
解决方案
前端修改:为每一行单独创建表单
将每一行的按钮放入独立的<form>中,确保提交时仅携带当前行的Application_id和对应按钮的status值,推荐简洁写法:
<div class="body table-responsive"> <table class="table table-hover" id="customers"> <thead> <tr> <th style="width: 1%" >S No.</th> <th style="width: 10%" >Name</th> <th style="width: 5%" >Experience</th> <th style="width: 5%" >Main Skills</th> <th style="width: 10%" ><center>#</center></th> </tr> </thead> <tbody> {% for Application in Job.applications.all %} <tr> <th scope="row"> {{ forloop.counter }}</th> <td><a style="font-size: medium;" href="{% url 'application' Application.id %}">{{Application.created_by.username}}</a></td> <td>{{Application.Experience}}</td> <td>{{Application.Skills}}</td> <td><center> <!-- 每行单独的表单,包含两个操作按钮 --> <form method="POST" action="#"> {% csrf_token %} <input type="submit" value="Shortlist" name="status" > <input type="submit" value="Reject" name="status"> <input type="hidden" name="Application_id" value="{{ Application.id }}"> </form> </center></td> </tr> {% empty %} <p>No application for this job yet...</p> {% endfor %} </tbody> </table> </div>
后端修改:完善状态更新逻辑
在视图函数中,将获取到的status值赋值给Application对象的对应字段(需与模型中字段名一致),再执行保存操作:
def JobDashboard(request, jobs_id): Job = get_object_or_404(job, pk=jobs_id, created_by=request.user) if request.method == 'POST': application_id = request.POST.get("Application_id") status = request.POST.get("status") # 确保参数存在再执行更新 if application_id and status: query = Application.objects.get(id=application_id) # 假设模型中状态字段名为status,若不同请替换为实际字段名 query.status = status query.save() return render(request, "View_Dashboard_job.html", {"Job": Job})
内容的提问来源于stack exchange,提问作者Shivi Dutt
相关产品推荐
相关产品推荐

