python - 当我将引导程序添加到我的 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 以使模态消息显示正确的数据?
解决方案
错误的模态显示是因为所有模态元素都使用相同的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>
推荐阅读
- node.js - 为什么 xstate 转换在 nodejs 中对我不起作用?
- python - 不能直接使用多进程池的结果
- excel - 仅当对应的单元格是数字时才求和,如果不是,则将剩余的 % 分配给其他值
- python - 在同一列上应用两个过滤器
- python - 我的 tensorflow 模型不支持多分类,这是为什么呢?
- javascript - Discord bot 活动但不响应命令 (js)
- java - 如何使用共享首选项保存任务的日期和时间?
- excel - 一个单元格中的两个 vlookup 函数
- laravel - SQL:选择不同但将所有一列添加到不同的结果
- php - 使用 SQL 优化 laravel 模型