Динамическая загрузка данных в Django Modal
Я пытаюсь реализовать способ динамической загрузки информации в модальное окно, чтобы сделать быстрый предварительный просмотр для моего сайта электронной коммерции. Любая помощь будет оценена по достоинству, я не уверен, в каком направлении мне двигаться. Я пытался играть с Javascript и создать функцию onclick для обновления div, но пока не добился успеха. Пожалуйста, прокомментируйте, если какая-то часть моего вопроса непонятна.
Прилагается скриншот того, что отображается на моей стороне, чтобы получить представление о том, что я пытаюсь сделать.
https://gyazo.com/e0168c6d41a19071a95e8cecf84e37a9
store.html
models.py
class Product(models.Model):
name = models.CharField(max_length=150, null=True)
price = models.FloatField()
image = models.ImageField(null=True, blank=True)
specialObject = models.BooleanField(default=False)
def __str__(self):
return self.name
@property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
Вы можете назначить id
на h6
, img
и button
tags
соответственно, а затем использовать javascript
для обновления модала, извлекая необходимые идентификаторы.
Например:
{% for product in products %}
...
# Here you can use the product id to mark each tags within the iteration
<img id="image-url-{{ product.id }}" class="thumbnail" src="{{ product.imageURL }}">
# Applying the same concept as above to the h6 and button tags
<div class="box-element product">
<h6 id="product-name-{{ product.id }}"><strong>{{ product.name }}</strong></h6>
<hr>
# Can use the onclick event here on the button and pass the button's id which is the product's id itself to be dealt with in js.
<button type="button" class="btn btn-outline-success" data-toggle="modal" data-target="#myModal" id="{{ product.id }}" onclick="updateModal(this.id)">View Details</button>
...
</div>
...
{% endfor %}
# I'd suggest moving the modal outside of the forloop as well...
<!-- Modal -->
...
<!-- Modal content-->
...
<h4 class="modal-title" id="modal-title"></h4> # Leave here blank...
...
<img class="thumbnail" src="..." id="modal-image"> # Assign an id here as well.
...
...
# Javascript
<script type='text/javascript'>
function updateModal(id){
let product_name = document.getElementById("product-name-" + id).textContent;
let image_src = document.getElementById("image-url-" + id).src;
# Now setting the modal title and image with the values above...
document.getElementById("modal-title").innerHTML = product_name;
document.getElementById("modal-image").src = image_src;
}
</script>