Skip to content
Advertisement

Using a variable to for loop using django

I’m very new to python and django framework. I’m facing a minor issue of not being able to assign a variable to my for loop.

In my html file there are buttons and a list (rendered using a loop).

for ex:

Buttons

JavaScript

Inside script tags i’m updating the variable value as

JavaScript

Also i have a loop like following in the same html file

JavaScript

Here i want to replace base according the button clicked.

For ex:

JavaScript

Clicking on the above button should make the for loop as

JavaScript

From i read you can do something like this to assign a value to a variable.

JavaScript

Any help is appreciated

Advertisement

Answer

Also i have a loop like following in the same html file

{% for layer in base %} {{layer.title}} {% endfor %}

Here i want to replace base according the button clicked.

In short, Django is a server-side framework and it cannot directly respond to any client-side activity. You cannot do it effectively without client-side libraries like React, JQuery, etc.

Workaround 1

You can make a new request to the server on click and re-render the entire page with new parameters.

urls.py

JavaScript

views.py

JavaScript

my_template.html

JavaScript

The base will have dynamically generated data on every request.

Workaround 2

You can, however, render all the data on the page and control it using collapse in bootstrap https://getbootstrap.com/docs/4.5/components/collapse/

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement