首页 > 解决方案 > 当我将引导程序添加到我的 django 项目中时,模式消息未显示正确的数据

问题描述

**homepage.html**

{% for country in countries %} 
        <tr>
          <th scope="row">{{ country.id }}</th>
          <td>{{ country.name }}</td>
          <td align="center"><a class="btn btn-warning" href="{% url 'edit_country' country.id %}">Edit</a></td>
          <td align="center"><a class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#exampleModal">Delete</a></td>
          <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="exampleModalLabel">Delete post</h5>
                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                  Are you sure you want to delete {{ country.name }}?
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button>
                  <button type="button" class="btn btn-danger" href="{% url 'delete_country' country.id %}">Delete</button>
                </div>
              </div>
            </div>
          </div>
        </tr>
        
        
        {% endfor %} 

视图.py

def homepage(request):
    countries = Countries.objects.all()
    context = {'countries':countries}
    return render(request,'homepage.html',context)

模型.py

class Countries(models.Model):
    name = models.CharField(max_length=75)
    landmark = models.CharField(max_length=100,null=True)
    food = models.CharField(max_length=100,null=True)
    entertainment = models.CharField(max_length=100,null=True)
    image = models.ImageField(upload_to='travel', default='default.png',null=True)
    
    def __str__(self):
        return self.name

这里我有一个问题,当我使用 Django 组件 Modal 时,虽然我使用 for 循环来传递参数country,但可能会出现模态消息,但它没有显示正确的{{country.name}}数据。我尝试单击第二行上的删除按钮,但消息仍然只显示第一个对象的数据而不是第二个对象的数据。请问是否存在我错误地放置模态块的问题,或者我应该使用 JavaScript 以使模态消息显示正确的数据?

模态消息

标签: pythondjangodatabaseweb

解决方案


错误的模态显示是因为所有模态元素都使用相同的id,所以当您单击任何模态时,它总是显示第一个模态#exampleModal

因此,您可以做的是更新id模态的 以包含country.id以及id引用 的目标。这将使每个模态在 HTML 中都是唯一的,并允许在单击表格行时显示正确的切换。

例如

<tr>
...
<td align="center"><a class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#exampleModal-{{country.id}}">Delete</a></td>
<div class="modal fade" id="exampleModal-{{country.id}}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
...
</div>

推荐阅读