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

<li><a class="layer-item" href="#" onclick="selectLayer('base')" title="Base layer">Base layer</a></li>
<li><a class="layer-item" href="#" onclick="selectLayer('soil')" title="Soil layers">Soil layers</a></li>

Inside script tags i’m updating the variable value as

<script>
  var layerType = "";
  function selectLayer(layer){
    layerType = layer;
  }
</script>

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

{% for layer in base %}
   <div class="col-4">
      <span class="base-layer-title d-block">{{layer.title}}</span>
   </div>
{% endfor %}

Here i want to replace base according the button clicked.

For ex:

<a class="layer-item" href="#" onclick="selectLayer('soil')" title="Soil layers">Soil layers</a>

Clicking on the above button should make the for loop as

{% for layer in soil %}
    <div class="col-4">
       <span class="base-layer-title d-block">{{layer.title}}</span>
    </div>
 {% endfor %}

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

{% with name="World" %} But not sure how to implement it in my issue.

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

path('my_pattern/<slug:my_layer>', myview)

views.py

def myView(request, my_layer):
   # your logics
   base = get_layer_data(my_layer) # <-- logic to get list dynamically
   return render(request, 'my_template.html', context={'base':base})

my_template.html

{% for layer in base %}
   <div class="col-4">
      <span class="base-layer-title d-block">{{layer.title}}</span>
   </div>
{% endfor %}
...
<a class="layer-item" href="/my_pattern/soil" title="Soil layers">Soil layers</a>
<a class="layer-item" href="/my_pattern/some_other_layer" title="Some other  layers">Soil layers</a>
...

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