How can I dynamically assign a variable to the ID of a <div> element in a Django template?

Discovering the world of Django template language has been quite an interesting journey for me, especially as I experiment with bootstrap collapses to showcase my items. Let's take a look at the code snippet below:

{% for item in items %}
<div id="accordion">
  <div class="card">
    <div class="card-header" id="headingOne">
      <h5 class="mb-0">
        <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          {{item.item_name}}
        </button>
      </h5>
    </div>

    <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion">
      <div class="card-body">
        {{item.description}}
      </div>
    </div>
  </div>
</div>
{% endfor %}

This particular implementation is based on the collapse feature within Bootstrap documentation which can be found here. However, a challenge arises when all items have the same id 'collapseOne'. Consequently, clicking on any item triggers the collapsing or expanding of every item on display. I did try using

id="collapse{{item.item_name}}"
without much success. Is there a way to dynamically pass variables into the div ID attribute?

Answer №1

give this a shot

{% for element in elements %}
<div id="accordion">
  <div class="card">
    <div class="card-header" id="heading{{forloop.counter}}">
      <h5 class="mb-0">
        <button class="btn btn-link" data-toggle="collapse" data-target="#collapse{{forloop.counter}}" aria-expanded="true" aria-controls="collapse{{forloop.counter}}">
          {{element.element_name}}
        </button>
      </h5>
    </div>

    <div id="collapse{{forloop.counter}}" class="collapse show" aria-labelledby="heading{{forloop.counter}}" data-parent="#accordion">
      <div class="card-body">
        {{element.description}}
      </div>
    </div>
  </div>
</div>
{% endfor %}

https://docs.djangoproject.com/en/3.1/topics/templates/#the-django-template-language

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 horizontal scrollbar in Chrome is unexpectedly activated, despite elements being set to occupy the full screen width (100vw) using Tailwind and NextJS 13.4+

It took some time to identify the root cause of this issue within a larger project. Hopefully, this Question and Answer will be beneficial to someone else. Here is the scenario -- in a NextJS/Tailwind project, there is only one large vertical element on t ...

The issue of CSS errors encountered when incorporating Bootstrap with the millimeter unit for padding

<!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title></title> <!-- bootstrap --> <lin ...

Interact with a Bootstrap dropdown menu using Selenium in Python

Currently facing an issue while trying to select an item from a bootstrap dropdown using Selenium. I am able to click the dropdown to show the options, but unable to click on any option. Various attempts have resulted in the following error: TypeError: ...

Using dateutil.parser.parse() will result in the loss of timezone details

My challenge lies in utilizing dateutil.parser.parse() to parse the default output of str(datetime.datetime.now()) while maintaining timezone-aware datetimes. Unfortunately, it appears that parse() disregards the timezone information and replaces it with t ...

Create a "thumbs up" feature in Django that functions without the need to refresh the page

I am striving to recreate the functionality of the "like project" feature found on ruby-toolbox (specifically, the heart button). By clicking the "like" button, it adds that particular project to your list of liked projects without needing to refresh the ...

Is there a way to dynamically import several CSS files in React Native depending on the data stored in this.state?

How can I dynamically import multiple CSS files in a React Native project based on language? import React, { Component } from "react"; if(this.state.language === "he"){ import styles from "./he"; }else{ import styles from "./en"; } I attempted the ab ...

What are some ways to implement SQL subqueries in Django ORM?

Looking to fetch recent average data using Django ORM. select product_name, AVG(price) as avg_price from ( select procuct_name, price, deal_date from deal_history order by deal_date desc ) R I attempted to achieve this ...

When an absolute positioned element exceeds the right border of its relative parent, its width will be truncated

When position: absolute; divs are placed inside or around a position: relative; parent, their height and width are based on the size and length of the text they contain. However, if one of these divs extends beyond the right border of the relative parent, ...

Unable to start Django CRM

Just starting out in django development and trying to run a django crm project that I downloaded from code.google.com. The source code can be found here: . After running the sample project, I encountered errors such as "no module named Django_notify ...

Absolute Positioning Problem

When I attempt to insert elements as static html text, everything functions correctly. However, when I try to insert elements at runtime (using arrays of data from the server), I encounter positioning issues with absolute. Here is the simplest example to r ...

Expand the space between each pair of rows within a table

After implementing the code below: HTML <table> <tr> <th>Company</th> <th>Contact</th> <th>Country</th> </tr> <tr> <td>Alfreds Futterkiste</td ...

Retrieving specific values for each key in JSON using PHP

Looking for a solution with PHP to extract specific information from JSON files based on set criteria. Here is an example of part of the JSON data: "Main": [{ "count": 7, "coordinates": [89,77], "description": "Office", },{ "count": 8, ...

Steps for declaring CSS values with fallbacks in case of unsupported values

I'm looking to utilize the overflow: overlay property in Chrome, and overflow: scroll in Firefox. Simply declaring the overlay value causes Firefox not to scroll at all, even though I know it's not standard. My question is: what's the optim ...

Attempting to alter the background image through the action of clicking on an image using jQuery, HTML, and CSS

I have created custom weather icons like a sun, cloud, and rainy cloud using Photoshop. My goal is to allow users to click on these icons and change the background image of the website's body. However, despite my efforts, clicking on the images does n ...

Revamping the appearance of Youtube's DOM elements to enhance user experience

Each Youtube video includes a column div with two children: primary and secondary. https://i.sstatic.net/c4ayc.png https://i.sstatic.net/8bFf3.png The primary div contains a 'ytd-comments' element which houses all comments. I attempted to move ...

Dividing the webpage background into separate sections to showcase a variety of colors, patterns, and more

I'm in the process of dividing the background on my website into distinct areas. My goal is to have the patterned area extend both horizontally and vertically on either side until it reaches the edge of the visible webpage. Figuring out how to achiev ...

Steer clear of duplicating information between Django's ModelForm and Model

Is there a way to avoid redundancy between Django ModelForm and Django Model? For example, consider this basic Model: class Category(models.Model): name = models.CharField(max_length=128) and its corresponding ModelForm: class CategoryForm(forms.Mod ...

Tips for creating a mobile-friendly Bootstrap carousel that is both scalable and zoomable while maintaining the default slide functionality

I have a website using Bootstrap 4.x carousel. The layout is user-scalable with the following viewport meta tag: <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2, shrink-to-fit=no">. Currently, users can pinch to z ...

Troubleshooting Django static file issues in production environment version 1.2

After successfully running my code in the testing environment (DEBUG=TRUE), I encountered an issue when switching to DEBUG=FALSE where static files were not loading. My application setup includes: python3 manage.py collectstatic --no-input --clear python3 ...

Updating the division of a base template in Django without reloading it after a form submission action

I am looking to implement notifications in my base template, similar to the setup on the top left corner of Stack Overflow. I understand that this can be achieved by creating a custom template tag or a custom context processor. However, my specific requir ...