'Changing the inner Element of HTML using Javascript to present Django For Loop
I am currently in the process of the basics of Javascript and I know Django. So I am trying to use javascript to show elements in HTML for a Django For Loop.
The purpose of doing this is that I understood that presenting data using Javascript doesn't require the page to be refreshed, so I decided to give it a try.
To explain more my question here is an example of what I did.
I have a list of name of users who likes a posts and there are presented in the following format in the template:
<div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
{% for user in post_likes %}
<span class="dropdown-item" >{{ user.username }}</span>
{% endfor %}
So I added an id to the span and added the following script related to javascript:
<div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
{% for user in post_likes %}
<span id="id{{ forloop.counter }}" class="dropdown-item" >{{ user.username }}</span>
{% endfor %}
</div>
<script>
var element = document.getElementById("id{{ forloop.counter }}");
element.innerHTML = "{{ user.username }}";
</script>
When a new user likes the post his name should appear directly in this loop without the page refreshing but it is not happening and the name of the logged-in user is the one and appearing.
I am not sure if this is the correct way to integrate Javascript and Django together, but I thought of trying and I searched for answers but didn't find something solid.
My question: Is there something that I should fix in my code to present the data in the template to avoid the page refreshing?
Update I have updated by code for the script and hmtl using forloop.counter but the page needs to be refreshed to view the new names added to the list
Solution 1:[1]
This is not a whole answer, but I think there is a problem in your code:
{% for user in post_likes %}
<span id="id01" class="dropdown-item" >{{ user.username }}</span>
{% endfor %}
This results in several span with same id. Consider using forloop.counter.
Solution 2:[2]
Not that simple, if you want to send live data you need to implement something like Django Channels, and send data through websockets
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | albar |
| Solution 2 |
