Link Static Images with Javascript in Django

So, I am working on a Django project and trying to figure out how to get Javascript to render images from my static directory. I changed the settings.py settings for loading static files (images, js, etc.) from myproject / static and my templates from myproject / templates. Now at the top of each of these patterns I have the following line:

{% load staticfiles %} 

which allows me to upload images like this in a template:

 <img src="{% static "images/someImage.jpg" %}" width="65" height="36" alt="SomeImage"/> 

Now it works very well - loading the image and displaying as expected on the page. However, I am trying to do this (well, my teammate is all the same):

 <p><script src="{% static "js/getHeader.js" %}" type="text/javascript"></script></p> 

This line is in the same file with the two above lines. GetHeader.js file:

 var time = new Date(); var month = time.getMonth(); var day = time.getDate(); var year = time.getFullYear(); if (month == 1 & day == 23 & year == 2013) { document.write('<img src="{% static "images/anotherImage.png" %}" width="680" height="210" />'); } else { document.write('<img src="{% static "images/yetAnotherImage.png" %}" width="680" height="210"/>'); } 

To clarify, the idea is to print a different headline on a specific predetermined day. I'm trying to save any / html images separately from Python code, displaying templates for obvious reasons, so I don't want to just pass the image name as a parameter. The code itself works fine, however, when the page loads, the name alt appears, but the image itself is missing; just one of these generated empty fields "image not found".

It might be worth mentioning that if I embed this Javascript in the actual HTML page that the image renders perfectly. It's also in the development environment, not production — I'm going to deal with this later on in the road.

What gives? I realized that since this line should be written to the document containing the "load staticfiles" line above, then the image will simply display along with the rest of the HTML. Any suggestions on how to fix this or perform it differently will be greatly appreciated.

+4
source share
1 answer

getHeader.js in no way associated with django. This is just a text file downloaded by the browser. Therefore, he does not know about django syntax, for example {% static%} or {{foo}}.

There are several ways around this. The usual way is to define a global javascript variable that is your STATIC_URL , which you can reference in future JS files.

 <script type="text/javascript"> DJANGO_STATIC_URL = '{{ STATIC_URL }}'; </script> 

Another is to use something like a Django Compressor that can render JS through the django template system. https://github.com/jezdez/django_compressor

+8
source

Source: https://habr.com/ru/post/1493775/


All Articles