Below is the simplified version of my code
view.py:
context['colorObj'] = Colors.objects.all()
Now on template, I can just loop through {{colorObj}} to get the individual values inside the object. However on JavaScript, this is not the case.
If I want to assign to a variable my colorObj, it just does not work(or maybe I am wrong). Here is I first thought I should do:
JavaScript:
var colorObj = {{colorObj}};
the value of colorObj is still empty, and there are warning marks on the {{}}. Others suggested to use "" on the Javascript like var colorObj = "{{colorObj}}";
but JavaScript just treat this as a simple String.
Other suggestion is this:
from json import dumps
...
colorObj = Colors.objects.all()
context['colorObj'] = dumps(colorObj)
Then on JS:
var colorObj = {{colorObj| safe}};
But I got an error Object of type QuerySet is not JSON serializable
pointing the error to the dumps line.
Note, I am using Django3.1.5
Though I asked about how to get the data from db to Javascript with this method, I proceeded to a different method since it matches my use case. I used @Mahdi Firouzjah's answer for this.