New to django here. I'm having trouble connecting with javascript code from django python. I think I've followed the documentation on project configuration.
HTML template:
<!DOCTYPE html>
<html lang="en">
<body>
Test template<br>
{% csrf_token %}
{% load static %}
{{ form | safe }}
<script type="text/javascript" src="{% static '/grid_1/test_script.js' %}"></script>
Test template end<br>
</body>
View function:
def test_view(req: djhp.HttpRequest):
form = forms.TestForm(); vals = dict()
vals["test_val"] = "This is a test"
return djsc.render(req, "test_template.html", vals)
JavaScript code:
alert("test script start")
var x = "{{ test_val }}"
alert(x)
The second javascript alert displays "{{ test_val }}" instead of "This is a test". So it looks like django is not processing the .js file. Any help for this newbie is much appreciated!
That is fully expected behavior. Django will only replace values inside the HTML template, but given that your JavaScript is (like you add in your code) "static" and not in the original file, those values don't get replaced. The same applies for basically any templating framework. One option is to create an application/json
script embedded into your HTML, like the following:
<!-- probably somewhere in <head> -->
<script type="application/json" id="ssr-data">{{ data }}</script>
and in your Python you would stringify a dictionary containing such values and pass it to the view as data
(e.g. using the Python json lib: json.dumps({ "test_value": 23 })
). To access it from your JS you can simply do something like:
const data = JSON.parse(document.getElementById("ssr-data").innerText)
console.log(data.test_val) // 23