score:0

Accepted answer

the question needs more context to help us understand your goal. it seems you are mixing python with javascript data structures.

my general recommendation is that you first prepare the python data structure to what you will need and then convert it to json. looping within django template language should be used only on simple cases.

if you use django>=2.1 you can use json-script template tag

 {{ data|json_script:"my-data" }}

https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#json-script

if not, you can use

# views.py
import json
def foo(request):
    databf = {"a": [{"c": [1,2,3,1,1]},{"d": [1,2,3,1,1]}]}
    # here you can manipulate the data accordingly to what you need
    data = json.dumps(databf)
    return render(request, "index.html", context={"data": data})

on the template side

<script>
    const datajs = {{ data | safe }};
</script>

the datajs is a javascript object that you can work with.

i've made an example that you can check https://repl.it/@ivanpereira/python-to-javascript-django-template

score:0

you can do this in 2 ways.

  1. store all values in a list, which javascript will consider as json array, and loop over using javascript itself. this way you won't be able to update records from server and all values that has to be looped over should be pre-fetched.

  2. you can use ajax call to pass the selected index from javascript and return the new array and update that in the template using javascript itself.


Related Query