**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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句