Hi there, I am working on an ecommerce store in Django. I want to know that how do I use the database data passed to templates using render()
method, conditionally through JavaScript?
For example, let’s say I have a following models.py
:
from django.db import models
class Suit(models.Model):
title = models.CharField(max_length = 100, verbose_name = "Title")
img = models.FileField(upload_to = 'suit-products/', null = True, verbose_name = "Picture")
def __str__(self):
return f"{self.title}"
class Buttoning(models.Model):
title = models.CharField(max_length = 100, verbose_name = "Title")
img = models.FileField(upload_to = 'buttonings/', null = True, verbose_name = "Picture")
def __str__(self):
return f"{self.title}"
and following views.py
from django.shortcuts import render
def index(request):
suit_prods = Suit.objects.all()
buttoning = Buttoning.objects.all()
context {
"suit_prods": suit_prods,
"buttoning": buttoning
}
return render(request, "index/index.html", context)
and following index.html
(template):
{% for element in suit_prods %}
<li>
<a href="#">
<div id="menu">
<img src="{{ element.img.url }}" />
<span>{{ element.title }}</span>
<span></span>
</div>
</a>
</li>
{% endfor %}
Now what I want is, if the clicked element
in the list items in index.html
has the title
as "two_piece_suit"
then show items of {{ buttoning }}
as a list, otherwise pass.
If I explain it more using some JS syntax, then I want following kind of behaviour:
<scrip>
var suit_menu = document.getElementsByClassName("menu");
for(var i = 0; i < suit_menu.length; i++) {
if(suit_menu.text == "two_piece_suit") {
{% for element in buttoning %}
<li>
<a href="#">
<div id="buttoning">
<img src="{{ element.img.url }}" />
<span>{{ element.title }}</span>
<span></span>
</div>
</a>
</li>
{% endfor %}
}
}
</script>