Django中modal-body仅显示hostels模型首个对象的问题排查
问题根源分析与解决方案
这问题其实很典型——所有模态框(modal)共用了同一个id="exampleModalCenter",浏览器在处理重复id的元素时,只会识别页面中第一个匹配该id的元素,所以不管你点哪个按钮,触发的都是循环生成的第一个模态框,自然显示的是第一个hostel的数据。
而按钮上的{{hostel.hostel_name}}能正常显示,是因为按钮本身在{% for hostel in hostels %}循环内部,每个按钮都会对应当前循环的hostel对象,属于独立的DOM元素,没有id冲突的问题。
修复步骤
你需要给每个循环生成的模态框设置唯一的id,同时让对应按钮的data-target指向这个唯一id,具体修改如下:
{% for hostel in hostels %} <div class="container" style="width: 48%;margin: 10px;height: 140px;background-color: white;display: inline-block;position: relative;"> <a href="{{hostel.pk}}/deletehostel/" style="color: white;position: absolute;top: 0px;right: 0px;margin: 0px;padding: 0px;padding-right: 5px;padding-left: 5px;background-color: red"> X </a> <a href="{{hostel.pk}}" style="text-decoration: none"> <h1 style="text-align: center;">{{hostel.hostel_name}}</h1> <p style="text-align: center;">total beds: {{hostel.capacity}}</p> </a> <!-- 修改按钮的data-target,用hostel的pk生成唯一标识 --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter-{{hostel.pk}}" style="display: block;margin: auto"> {{hostel.hostel_name}} <!-- 这里替换成你要的 hostel_name --> </button> <!-- 修改模态框的id,和按钮的data-target对应 --> <div class="modal fade" id="exampleModalCenter-{{hostel.pk}}" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Edit details here</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <input type="text" class="form-control" value="{{hostel.hostel_name}}" name="" placeholder="hostel name"> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> </div> {% endfor %}
关键修改点
- 按钮的
data-target改为#exampleModalCenter-{{hostel.pk}},利用每个hostel唯一的pk值生成目标选择器 - 模态框的
id改为exampleModalCenter-{{hostel.pk}},确保每个模态框的id唯一,和对应按钮的目标完全匹配
这样修改后,每个按钮都会触发对应hostel的模态框,modal-body里的内容也就会正确显示当前hostel的数据了。
内容的提问来源于stack exchange,提问作者user10070450
相关产品推荐
相关产品推荐

