0

I am new to django and eventually I learnt the use of static files in Django and to my relief I was finally able to load the files while hardcoding the file name in the {%static filename.jpg %}. However, when I tried to create a string by replacing the hardcoded filename.jpg with the dynamic file name, I wasn't getting the output.

Not working code snippet:

<script>
 image_name = "1.png" 
 static_start = "{% static '"
 static_end =  "' %}"
 image_src = static_start.concat(image_name, static_end)
 window.alert(image_src) 
 var para = document.createElement("img");
 {% load static %}
 para.setAttribute("src", image_src)
 var element = document.getElementById("div_test");
 element.appendChild(para);
</script>

Working Code snippet:

 

<script>     
 var para = document.createElement("img");
 {% load static %}
 para.setAttribute("src", "{%static '1.png'%}")
 var element = document.getElementById("div_test");
 element.appendChild(para);
</script>

What I am trying to do is that, I have a bunch of image files that I am getting from somewhere through an API and I am storing them in the static folder. After downloading those image, I am trying to load them on my webpage, for that I am using the static file and getting the file name dynamically as I do not know what would the file name of the downloaded file.

The point is that string concatenation isn't working, while directly passing the string is.

Any help would really be appreciated.

P.S.: Apparently in the example shared above I am simply using 1.png which would eventually be replaced by the name of the file I wish to display.

Working code using get_static_prefix (the way I actually wanted)

<script>
    image_name = "1.png"     
    var para = document.createElement("img");
    {% load static %}
    para.setAttribute("src", "{% get_static_prefix %}" + image_name)
    var element = document.getElementById("div_test");
    element.appendChild(para);
</script>
Afsan Abdulali Gujarati
  • 1,375
  • 3
  • 18
  • 30

2 Answers2

0

I think I understand what you are trying to do here, but I don't think it is possible. Django templates are rendered on the server, and JavaScript is rendered on the client-side. You are trying to create the template tag with JavaScript, but the template tags won't be evaluated on the client-side, they will just be strings.

briancaffey
  • 2,339
  • 6
  • 34
  • 62
0

So after referring to other posts, I realized what I was doing wrong. I believe there was something that wasn't right about string concatenation and the escape characters and therefore Django has an option for get_static_prefix and that is was I was supposed to use instead of that stupid string concatenation. I have edited my question with the correct working response, exactly the way I wanted it to.

References: Stackoverflow question, Django tutorial

Afsan Abdulali Gujarati
  • 1,375
  • 3
  • 18
  • 30