Skip to content
Advertisement

How to include Django static URL using JavaScript?

I have a django application storing static images on digital ocean spaces. I can easily display these static images in my template by doing:<img>{% static 'images/my_image.png' %}</img>

If I inspect the HTML page after this loads, I will see something like:

https://nyc3.digitaloceanspaces.com/nameofmyspace/nameofmyspace-space-static_DEV/images/my_image.png?AWSAccessKeyId=XXXXXXXXXXXXXX&Signature=XXXXXXXXXXXXXXXXXX%3D&Expires=1621600823

But now I want to have this image change dynamically using javascript.

So I tried:

document.getElementById(id+"dynamicImage").src = "{% static 'images/my_image_2.png' %}";

Which almost works, but the image does not load. And the reason for this is after inspecting the src that the javascript supplied:

https://nyc3.digitaloceanspaces.com/nameofmyspace/nameofmyspace-space-static_DEV/images/my_image.png?AWSAccessKeyId=XXXXXXXXXXXXXX&amp;Signature=XXXXXXXXXXXXXXXXXX%3D&amp;Expires=1621600823

You can see wherever there was an & it appended amp; to it. What is the correct way to do this?

I can think of 2 ways to correct this, but they seem hacky.

  1. I could hard code the URL’s into the javascript, which will be an updating nightmare as things change
  2. I could do <img id = 'my_image' hidden >{% static 'images/my_image.png' %}</img> for all the links I plan on using, then access this URL in the javascript using let URL = document.getElementById("my_image").innerHTML;. This will be less of an updating nightmare, but seems hacky and must be a better way.

Advertisement

Answer

I solved it by doing:

document.getElementById(id+"dynamicImage").src = ("{% static 'images/my_image_2.png' %}").replace(/&amp;/g, "&");

.replace(/&amp;/g, "&") will replace all &amp; with &. The/ and /g is regex to replace all.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement