0

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!

1

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you code - that makes perfect sense. I've been working through a tutorial and I guess the assumption they make is that no .js code needs to be processed. I'll move forward with embedding the javascript in the html files, although I would prefer to store this in separate files if possible. Thanks for the help from a Django newbie!
@HankBrandenburg great. Just in case it's not clear, the data needs to be in your template file, but your JS can always be in another file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.