Unable to load concatenated static file source - javascript

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>

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.

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

Related

How to add img elements with Javascript when using Django?

I am trying to dynamically insert img elements to the website I am building which uses Django for the back-end. The images change often so I pass the src from Python to Javascript like this:
views.py
path='{% static "../static/assets/'+image_name+'" %}'
response = render(request, 'main.html',{'image_path':path})
return response
Then I declare a global variable in the template so I can use this in the .js files.
main.html
var imagePath = {{image_path|safe}}
Then I use Javascript to pass this as src to new img elements. However, when I do it, Django cannot find images. When I put the string as src to a img element manually, it works.
Does anyone know how to solve this?
You need to use this:
from django.templatetags.static import static
path = static(f'assets/{image_name}')
response = render(request, 'main.html',{'image_path':path})
return response

How to use Javascript to get current file name and use as a variable in Pug/HTML template?

I would like to pass the file name to the tag in an html document. I would therefor like to grab it and put it in a variable. I am using Pug, so can use javascript before compiling to html.
This is obviously, obviously not correct code, but is the idea of what I need:
let title tag === filename.pug
I have tried this and it works in the browser, but it works off the url and I would like to do it off the OSX file path.
var filename = (location.pathname.substring(location.pathname.lastIndexOf("/") + 1)).replace('.html','');
document.getElementById("title").innerHTML = filename;

Use a image from a server in Django template

Right now I'm storing the image in the static folder, but this is not working in production.
View
local_path = "checkimage/static/{}".format(image_file_name)
download_blob(server_path, path + '/' + image_file_name, local_path)
javascript
let img = '<img src="/static/' + image_file_name + '/>';
Which is the correct approach to do this? They are several images and very heavy.
Rather than downloading a static file from another website, you can just access the image via HTML in your template file:
<img src="https://media.giphy.com/media/rl0FOxdz7CcxO/giphy.gif" alt="gif of someone celebrating, with text 'It's happening'">
If, for whatever reason, you don't want to access the image file in your template and you still want to download it, you'll need to move the downloaded file to staticfiles/ or to wherever you've configured your static files to be served from in settings.py. Putting the static file in app_name/static/ will not work in production.
If your image is part of a model's fields (ie ImageField) or uploaded, django sets up an url attribute to get the url of the image.
class ModelName(models.Model):
image = models.ImageField(upload_to='folder_name/')
...
Pass data with your views.
In your template:
let img = '<img src="{{data.image.url}}"/>';
And Do not forget to add this i settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Javascript (string) Equality with Django Template

I'm new in Javascript and this is my html code that contain django template :
I have img element which src attribute is "{% static 'basic/myImage.jpg' %}" which actually django template to load static file
<img src="{% static 'basic/myImage.jpg' %}" alt="img"/>
then i have script (javascript) let say main.js which aim is to select that img src attribute which will return literally "{% static 'basic/myImage.jpg' %}"
var myImg = document.querySelector('img');
var myImgSrc = myImg.getAttribute('src'); //return a string "{% static 'basic/myImage.jpg' %}"
my problem is when i try equality test in web console (inspecting element) :
myImgSrc === "{% static 'basic/myImage.jpg' %}" is return false
may be there is escape character or special character to represent my django template, can someone explain how to represent django template in literal js string. Thank you sorry for my bad english.
It's hard to tell exactly what you are trying to do, but I'll attempt to offer some suggestions.
When the template is rendered, {% static 'basic/myImage.jpg' %} is also rendered, so it becomes "/static/app/images/basic/myImage.jpg" or whatever. So your javascript evaluation will always be false.
If you need javascript to have the actual value returned by {% static 'basic/myImage.jpg' %}, then you will need to include the script in the template itself, rather than a separate main.js file.
So, at the bottom of your template.py file, you could have something like:
<script type="text/javascript>
var myImg = document.querySelector('img');
var myImgSrc = myImg.getAttribute('src');
var Foo = "{% static 'basic/myImage.jpg' %}";
if (myImgSrc === Foo) { // this should be true
// do something
}
</script>
Also, if main.js is included AFTER this script tag, it should have access to the values of myImgSrc and Foo.

Javascript to get .pdf file from partial match

Complete and utter javascript newbie here with a problem fetching .pdf files from a web server based on a partial match. I have made a program that outputs data to a webserver, and one of the components is a folder of .pdf files. I want to be able to click on a link that will pull up the corresponding .pdf file based on a value in the data table that's generated (I'm using slickgrid for this). Each of the .pdf files contains the value that's in the data table and serves as good query to the .pdf folder, and I've been successful at getting the .pdfs I want with the following code:
var value = grid.getData().getItem(row)['data'];
var locpath = window.location.pathname.substring(0,window.location.pathname.lastIndexOf('/'));
var plotsFolder = window.location.protocol + "//" + window.location.host + locpath + "/CovPlots/";
var href = plotsFolder + value + ".pdf";
return "<a href='" + href + "'>" + value + "</a>";
The catch here is that sometimes the .pdf file that's generated is a concatenation of two or more (I've seen up to 4 so far) of the 'data' strings, separated by '_' as a delimiter for reasons not worth getting into. So, if the .pdf file is 'somestring.pdf', I can get it without problem. However, if the .pdf file is 'somestring_anotherstring.pdf', I can't figure out how to get that .pdf file if I have either 'somestring' or 'anotherstring' as the value of 'data'.
I've tried a ton of different things to get some kind of lookup that I can use to pull down the correct file based on a partial match. The latest attempt is with the FilenameFilter object in javascript, but without any knowledge of javascript, I'm having a hard time to get it working. I tried to create a new function that I could call as a lookup for the .pdf URL:
function lookup() {
File directory = new File(plotsFolder);
String[] myFiles = directory.list(new FilenameFilter() {
public boolean accept(File directory, String fileName) {
return fileName.match(value);
}
});
}
That only seems to thrown an error. Can anyone point me in the right direction to be able to download the correct .pdf file based on a partial match? I also tried to see if there was a jquery way to do it, but couldn't seem to find something that works. Thanks in advance!
Without support from the server, JavaScript cannot find a file from a partial filename. What you can do, however, is have a little script on the server that does the partial-filename-matching for JavaScript, and then JavaScript can ask the server to do the match, and then when it gets the match back, it can use that filename.
If you don't mind loading a whole index of all the PDFs at once, you could use this little Python script to generate an index in a nice, JavaScript-friendly JSON format:
#!/usr/bin/env python
# Create an index of a bunch of PDF files.
# Usage: python make_index.py directory_with_pdf_files
import os
import sys
import json
def index(directory):
index = {}
for filename in os.listdir(directory):
base, ext = os.path.splitext(filename)
if ext.lower() != '.pdf':
continue
for keyword in base.split('_'):
index[keyword] = filename
with open(os.path.join(directory, 'index.json'), 'w') as f:
f.write(json.dumps(index))
if __name__ == '__main__':
index(sys.argv[1])
Then you can just load index.json with jQuery or what-have-you. When you need to find a particular PDF's filename, you can do something like this (assuming the object loaded from index.json is in the indexOfPDFs variable):
var href = plotsFolder + indexOfPDFs[value];

Categories