What is the best way to implement buttons dynamically in multiple divs created by Django using JavaScript loops?

I have been working on a Django project where I've created several HTML divs. My goal is to add a single button to each div. https://i.sstatic.net/DEIqL.png

In the image provided, you can see a div with the class card-footer that I created using a Django for loop. I intend to include a blue colored like button in each of these divs through javascript. However, as shown in the image, the button is only being added to one div. Below is a snippet of my HTML template:

<div id="posts" class="card">
            <ul class="card-body">
                {% for posts in page_view %}    
                    <li class="card"> 
                         <div class="card-header bg-success">
                            <h5 class="card-title"><a class="text-light" style="text-decoration: none;" href="{% url 'profile' posts.user.id %}">{{ posts.user }}</a></h5> 
                            <h6 class="card-subtitle text-light">{{ posts.timestamp }}</h6>
                         </div>
                        <div class="card-body">

                            <h3 class="card-text">{{ posts.post }}</h3>
                        </div>
                        {% include 'network/like.html' %}
                    </li>
                {% empty %}
                    <h6>No post availabel 😔</h6>
                {% endfor %}
            </ul>     
        </div>

Here is the content of my network/like.html file:

<div class="card-footer">
   
    <form action="{% url 'likepost' posts_id=posts.id %}" id="likeform" method="POST" style="display: inline;">
        {% csrf_token %}
        <button id = "like" class="btn btn-link" type="submit">Like</button>
    </form>
    <small id="num_of_likes">{{ posts.likepost.all.count }}</small>
    
    {% block script %} 
        <!-- <script>
            let posts_id = "{{ posts.id }}";
        </script> -->
        <script src="{% static 'network/controller.js' %}"></script>
    {% endblock %}
    <button class="btn btn-link" style="text-decoration: none;">Comment</button>
    <a href="{% url 'postpage' id=posts.id %}" class="btn btn-link" style="text-decoration: none;">View Post</a>
    {% if request.user.id is posts.user.id %}
        <a href="{% url 'editpost' id=posts.id %}" class="btn btn-link" style="text-decoration: none;">Edit</a>
       
    {% endif %}
   
</div>

The issue arises when trying to add a like button within the card-footer div to all elements but only getting added to the first one. Here is my complete js code:

document.addEventListener("DOMContentLoaded",function(e){
    e.preventDefault()
    const likebtn = document.createElement('button');
    likebtn.setAttribute('class','btn btn-primary');
    likebtn.setAttribute('id','likebtn')
    document.querySelector('.card-footer').appendChild(likebtn);
    document.querySelector('#likebtn').innerHTML = "Like";
})

function like_function(likepost){
    document.createElement('button').innerHTML = "Love";
    fetch(`/likepost/${posts_id}`)
    .then(response => response.json())
    .then(result => {
        console.log("Updated.");
        if(result.is_like){
            document.querySelector('#like').innerHTML = "Unike";
        }
        else{
            document.querySelector('#like').innerHTML = "Like";
        }
    })
    location.replace("http://127.0.0.1/")
}

As a newcomer to javascript, I'm struggling to identify what's causing this issue. Any insights or advice would be greatly appreciated!

Answer №1

As per the documentation, using the {% include %} tag with variables within the template you want to include is not supported. It might be possible to achieve your desired outcome by using JavaScript, or you could simply replace the include tag with the entire network/like.html template.

It's important to note that the include tag serves as a way to “render this subtemplate and include the HTML”, rather than “parse this subtemplate and include its contents as if it were part of the parent”. This lack of shared state between included templates means each include operates as an independent rendering process.

While I haven't personally tested this method, another option could involve creating a custom include template tag, which is detailed here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The <g> tag fails to properly render within the <svg> element in Firefox

When running an Angular 6 application with ES6-style D3js modules, there are some issues on Firefox (Chromium, Chrome, Safari, and IE Edge work fine). Below is a sample of pseudo code (full production code is available below): <svg width="500" height=" ...

I noticed that when I am scrolling through my website, the navigation bar becomes hidden due

I'm facing an issue where my navbar disappears when I try to scroll to the second page of the website. Can anyone explain why this is happening, or provide a tutorial or course that I can reference? index.html This is the index.html file where ...

Unable to retrieve the value stored in the global variable

I recently updated my code to use global variables for two select elements in order to simplify things. Previously, I had separate variables for values and innerHTML which felt redundant. Now, with global variables like user and group initialized at docum ...

Seeking assistance with importing Json data into my HTML page using Python and AJAX

I've recently started delving into the world of AJAX and it's been quite some time since I last worked with JS. Currently, I'm using Python to generate valid JSON data, but my understanding hits a wall after that step. When I inspect the ele ...

Display a caption with a translucent color overlay when the mouse hovers over an image

I have created a code snippet that displays a caption with a semi-transparent red overlay when hovering over an image: HTML: <a href="http://www.domain.com/"> <div class="thumb"> <img src="http://www.domain.com/thumbnail.jpg" w ...

Creating HTML tables dynamically using PHP

I am currently working on creating a dynamic HTML table by querying the database using PHP. I am facing some challenges in understanding how to combine two different loops to ensure the correct generation of the desired table. <table><tr> & ...

Discover each *distinct arrangement* from a given array

I'm looking to generate unique combinations of element positions in a JavaScript array. Here's the array I am working with: var places = ['x', 'y', 'z']; The combinations I want are: [0,1], [0,2], [1,2]. Current ...

Disappearance of icon upon hovering in CSS

I am currently working with Angular JS (1.x) and I have a requirement to display tooltip text when hovering over an info icon. The tooltip text appears properly, but the issue is that the icon disappears when hovered over. It reappears once the hover is re ...

Guide on showcasing the values from two text fields with autocomplete suggestions in a third text field

Hey there, I have a search form that takes values from two text fields and combines them to populate a third text field for querying. <form name="form1" method="post" action="" autocomplete="off" oninput="sea.value = password.value +''+ passw ...

Issues with Firefox's -moz-placeholder functionality were observed not being functional as

I'm having trouble styling this placeholder in Firefox 13.0.1 Here is the input field with a placeholder: <input class="textFieldLarge" placeholder="Username" id="username" name="username" type="text" /> This is the CSS associated with it: . ...

Django combined with MongoDB

I am currently experimenting with integrating MongoDB and Django into my project. I have followed a step-by-step tutorial to ensure all the necessary components are set up correctly. The guide can be found here. However, I have encountered an issue when at ...

Retrieve JavaScript Variable Value when Button is Clicked via asp:HiddenField

Having limited experience with JavaScript and jQuery, I decided to make some modifications to a jQuery Slider for adjusting dates. You can check out what I've done so far here: http://jsfiddle.net/ryn_90/Tq7xK/6/. I managed to get the slider working ...

I am experiencing a problem where my webpage does not load properly when trying to access it

After setting up a route triggered by a specific click event using AJAX, I noticed that although my route is being called, the page content is not rendered as expected. Here is my AJAX function: function showProfile(user_id) { console.log("show pro:" + u ...

Do you need to finish the Subject when implementing the takeUntil approach to unsubscribing from Observables?

In order to prevent memory leaks in my Angular application, I make sure to unsubscribe from Observables using the following established pattern: unsubscribe = new Subject(); ngOnInit() { this.myService.getStuff() .pipe(takeUntil(this.unsubscr ...

Navigating through history using the pushState method and incorporating back and forward buttons

I am trying to implement back and forward buttons functionality with this ajax method The code is working well, and the URL in the browser is changing as expected However, when I click on the back and forward buttons, nothing happens (function(){ ...

Populate Vue 3 Element-plus Virtualized Table with actual data

As a newcomer to frontend development, I am currently working on integrating Element-plus Virtualized Table with actual data. Here is the basic structure of the example: const generateColumns = (length = 10, prefix = 'column-', props?: any) => ...

Navigating the challenges presented by CORS (Cross-Origin Resource Sharing) and CORB (Cross-Origin Read Blocking) when utilizing the FETCH API in Vanilla Javascript

Looking to update text on a website using data from a JSON file on another site? This scenario is unique due to restrictions - can't use JQuery or backend elements like Node/PHP. Wondering if vanilla JavaScript can solve the problem? While some worka ...

I have a JavaScript code stored as a string that I need to transform into plain JavaScript

If I have a variable in string format, for example suppose there is a JavaScript code inside it: var string="function myFunction(a,b){return a*b;}"; I want to convert this into pure JavaScript code format like so: function myFunction(a, b) { return ...

The issue of the hamburger icon appearing as "X" seems to only affect certain mobile phones, while it displays correctly on desktops and most other mobile devices. The problem appears to be specifically

On certain mobile phones, the hamburger icon displays as an "X" instead of three horizontal lines. This issue specifically affects all XIAOMI mobile phones on various browsers, while most other devices and desktops show the correct hamburger icon. The < ...

Navigating on a page using anchor tags within a dropdown menu

I'm in the process of creating a top navigation bar with dropdown functionality that appears when hovering over certain navigation items. Here's how it currently looks: $(document).ready(function(){ $('[data-toggle="tooltip"]').t ...