0

Pretty new to html/ javascript but basically in my views.py, I have a dictionary object created from user form data:

return render(request, 'graph/result.html', {'single_wv': single_wv})

How do I get that context variable into a javascript function (function is inside my html file)?

**Basically I want: index.html form data --> obtained inside views.py with POST --> some manipulation --> dictionary --> dictionary set as context variable --> call inside same index.html javascript function

Sorry if this question is kind of vague, I'm currently in the process of trying to figure everything out!

  • Possible duplicate of [Using JSON in django template](https://stackoverflow.com/questions/6286192/using-json-in-django-template) – thebjorn Nov 04 '18 at 10:21

1 Answers1

0

A common pattern would be to render single_wv somewhere in your graph/result.html like so;

<script>
    window.single_wv = {{ single_wv }};
</script>

Which would make it available to all scripts on your page. More advanced methods of injection depend on what type of front end scripts you have running.

If your value is a complex JSON object, see questions such as Using JSON in django template for more details.

Yuval Adam
  • 161,610
  • 92
  • 305
  • 395
  • Hey! Thanks for the tip; previously I tried var test = {{single_wv}}; but I think for some reason adding that line in messed up my entire interface somehow(?). Also I was under the impression that this would turn the variable into a string vs. a dictionary object; ^^w/ the format above, can I use the variable as a dictionary in my function? – user10602835 Nov 04 '18 at 08:20
  • should be fixed to `window.single_wv = "{{ single_wv }}";` That would be text, if you want it as an object you will need to send it as json with Ajax – elad silver Apr 16 '21 at 19:10