srttowers
srttowers

Reputation: 109

How do I pass string parameters from django to javascript function?

I have a problem calling a function with string parameters obtained from python.

python_var -> html calls the function of js with parameters obtained from python context -> js file

Browser console says: Uncaught ReferenceError
I am using Django template language to get the variable which is defined as a string in python.

foo.html

<script>
 libcharts_predict_k( {{title|safe}}, {{data|safe}})
</script>

I am sure the problem is only with Strings in JS function parameters because with arrays and numbers I didn't have any problem.
Browser tries to reference something but I am giving as a value

view.py

def second_view(request):
    title = "A long title"
    data= df['value'].values.tolist()
    context = {
               'data': data,
               'title': title
               }
return (request, 'app/foo.html', context=context)

*(Imports are fine)

Upvotes: 0

Views: 1504

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77892

Short answer: put quotes around your template vars:

libcharts_predict_k("{{title|safe}}", "{{data|safe}}")

And since data is a list you want to jsonify it before (in your view):

import json

# ....

data = json.dumps(df['value'].values.tolist())

Upvotes: 1

Related Questions