Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include Django static URL using JavaScript?

Tags:

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.
like image 786
MattG Avatar asked May 21 '21 12:05

MattG


1 Answers

I can't comment yet, But I did it this way with AWS, So here it is, If it is just what you want the users to see, You don't have to modify the actual Images stored in digital ocean, All you need to do is to generate a base64 image URL and send that "copy" image to the frontend and then use JS to do whatever it is u want the user to do, Even if you wish to modify the image, You can always save the Image to it's original name and set the "file_over_write" to True

like image 79
Hello World Avatar answered Sep 30 '22 16:09

Hello World