Tuesday, May 22, 2018

Passing values from Python to Javascript

I am trying to pass values from Django/Python to Javascript, and have it working to a degree, but need some assistance (obligatory: I'm new to Django so could be hosing this)

I have three files in play here, views.py, app.js, home.html. I can get the values passed to home.html as part of the render, but I can't get the code to work outside of the home.html file. Below is a very simplified example of what I'm doing. 

VIEWS.PY
return render(request, "home.html", {'data':data'})

HOME.HTML

<html>

     <head>

          <script src="{% static '/js/app.js' %}"></script>

          <script>

               myFunction({{ data | safe }});

          </script>

     </head>

</html>


APP.JS

function myFunction(vars){
    return vars
};



I would like to have the JS in the HTML file in the APP.JS file so I can centralize all Javascript, but cannot get it to work outside the HTML. I also tried sending the "data" to JSON using "json.dumps" but got an error that the data was not serializable, so went with this code posted above.

Can I do what I'm trying to do?

Thanks
Steve

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/c57509d3-fc80-4398-b04b-af1c390e9c85%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment