[Answer]-Simple application pass value from django views to javascript

1👍

You cannot pass values to javascript bypassing the template, unless you use an ajax call to start a separate request or unless you do something very unusual like embedding the data in a response header (don’t actually do this, it is not what response headers are for!). The response, which includes the header and the body (the body being the part generated by the template) is the sum total of the information your application provides to your client, so unless you generate an additional request and fetch an additional response with ajax, you have no other options.

If you don’t want to do that, then your options for passing information to the javascript via the template are basically the following:

  • Using an inline tag, create properly formatted javascript dynamically via the templating system. The example line you have, var value_from_django = {{ dict1 }}; is essentially what I’m talking about here, except that I’m not sure you can pass a dict through from django to javascript like that, because django’s text output of a dict in the template is unlikely to be exactly the correct formatting for a javascript variable declaration. So, instead you can…
  • Translate your data into JSON and put that into your template, and then process that with the javascript. (This is usually done with an ajax call, but there’s nothing stopping you from injecting the JSON data into the initial template directly.)
  • Or populate your HTML with the data you want and then use javascript to locate the HTML tag containing the data and parse the data out.

If you are trying to pass simple variables like integers, it might be easiest to do it with the first or third options. If you are trying to pass a more complex data structure like a dictionary, you will probably be better off using JSON (that’s what it’s for!)

I would like to give you more detailed and concrete instructions, but for that you will need to post more detail about what exactly is going wrong with your current approach and what your desired functionality is.

By the way: if it is at all feasible to include jquery on this page and use that instead of trying to use basic javascript, you should do so. It will make your life much, much easier.

Leave a comment