简体   繁体   中英

Passing a Django Object to Javascript

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.

you could use ajax in templates and __ serialize in backend side. then using javascript you're able to work with that object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM