skip to Main Content

I am making a Django website. In it I am trying to access a variable in view.py file in an external static JS file linked to my template.

I tried using the syntax var is_empty = "{{is_empty}}", but it didn’t work in a if statement where if(Number(is_empty) == 1), and also I tried creating a div in my body(with id = "temp") and adding an attribute data-dj = {{is_empty}} and then using var is_empty = document.getElementById("temp").getAttribute("data-dj");, but it was showing an error that cannot call getAttribute on null.

Please help!

2

Answers


  1. If is_empty type is boolean then try like this:

    if ("{{is_empty}}" === "true")
    
    Login or Signup to reply.
  2. You can declare a variable within a script tag in your Django template and then access this variable in your external JavaScript.

    In your Django template:

    <script type="text/javascript">
        var myVar = "{{ django_variable }}";
    </script>
    <script src="path/to/your/external.js"></script>
    

    In your external JavaScript file (external.js):

    console.log(myVar); // Access the Django variable
    

    Or you can use data attributes in HTML elements to store Django variables and then access these attributes from your external JavaScript.

    In your Django template:

    <div id="myElement" data-myvar="{{ django_variable }}"></div>
    <script src="path/to/your/external.js"></script>
    

    In your external JavaScript file:

    var myVar = document.getElementById('myElement').getAttribute('data-myvar');
    console.log(myVar);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search