Chartjs-Can I use a variable as index in for loop in python?

0👍

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

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.

Leave a comment