Django实现点击PSC检查列表链接弹出关联缺陷模态框求助
实现方案
1. 调整现有视图,补充检查记录ID
现有渲染用的inspections列表没有包含PSC检查记录的主键,无法关联查询对应缺陷,先修改views.py代码:
inspections = PSCInscpection.objects.filter( vessel_id=self.kwargs['pk']).order_by('-date') renderableInspections = [] for _insp in inspections: item = { "id": _insp.id, # 新增主键字段用于关联查询 "date": _insp.date.strftime("%Y-%m-%d"), "port": _insp.port, "country": _insp.country, "defects": _insp.number_of_defects, "detained": _insp.days_detained } renderableInspections.append(item) context['inspections'] = renderableInspections
2. 新增缺陷查询接口
新增一个接口用于根据PSC检查ID返回对应缺陷列表,示例用JSON接口实现:
新增视图函数
from django.http import JsonResponse def get_psc_defects(request, inspection_id): defects = PSCInscpectionDefects.objects.filter(pscinscpection_id=inspection_id).values() return JsonResponse({"defects": list(defects)})
配置URL路由
在urls.py中新增路由规则:
path('psc-defects/<int:inspection_id>/', get_psc_defects, name='psc_defects'),
3. 前端模板改造
3.1 调整缺陷链接属性
修改view.html中的缺陷链接,加上自定义属性存储检查ID:
{% if inspection.defects %} <a href="#" class="defect-link" data-inspection-id="{{ inspection.id }}">{{ inspection.defects }}</a> {% else %} 0 {% endif %}
3.2 新增模态框结构
在页面合适位置添加模态框HTML(以下是Bootstrap风格的示例,可根据你的UI框架调整):
<div class="modal fade" id="defectModal" tabindex="-1" aria-labelledby="defectModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="defectModalLabel">缺陷详情列表</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <table class="table table-bordered"> <thead> <tr> <th>缺陷代码</th> <th>缺陷描述</th> <th>责任方</th> <th>缺陷项代码</th> </tr> </thead> <tbody id="defectTableBody"> <!-- 缺陷数据将动态填充到这里 --> </tbody> </table> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button> </div> </div> </div> </div>
3.3 增加交互逻辑
在页面底部添加JS代码实现点击弹出功能:
// 引入jQuery或者用原生JS实现均可,以下是jQuery示例 $('.defect-link').click(function(e) { e.preventDefault(); const inspectionId = $(this).data('inspection-id'); // 请求缺陷数据 $.get(`/psc-defects/${inspectionId}/`, function(res) { const tbody = $('#defectTableBody'); tbody.empty(); // 渲染缺陷列表 res.defects.forEach(defect => { const row = `<tr> <td>${defect.defect_code || '-'}</td> <td>${defect.defect_text || '-'}</td> <td>${defect.class_is_responsible || '-'}</td> <td>${defect.defective_item_code || '-'}</td> </tr>`; tbody.append(row); }); // 弹出模态框 $('#defectModal').modal('show'); }); });
内容的提问来源于stack exchange,提问作者Letoncse
相关产品推荐
相关产品推荐

