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
Related
I've got a JS file called test.js, I'd like to pull in and utilize params that are attached to the extension of this file, but for some reason when I console log the results, I'm not seeing them.
How can I use the URL of a JS file to bring in variables, e.g:
<script src="test.js?var1=value1&var2=value2"></script>
The contents of my JS file is:
const search = window.location.search
console.log(search) <-- not seeing var1 or var2
What am I missing?
P.S: I cannot define a variable outside of the JS file and then use it within, surely there's a way to use the attached vars on the URL?
window.location is the location of the HTML document the script is running inside.
To get the value of the src attribute you need to use document.currentScript to get the element, then you can read its src property (and then you can parse it with URL()).
Unless you are sending the values to the server hosting the JS for server side processing, you'd likely be better off using data attributes instead.
<script data-foo="example">
console.log(document.currentScript.dataset.foo);
</script>
window.location.search returns the query string part of the URL[the current location of the document]. If you want to access the src of the script element, you may assign any unique identifier to the tag and may access the src property.
To access search parameters, you may use new URL(src)
let src = document.getElementById('src').src;
console.log('src - ', src);
const url = new URL(src);
console.log('search params - ', url.search);
<script src="test.js?var1=value1&var2=value2" id="src"></script>
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;
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/'
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
I'm using external template file and I want to use a partial inside the template file (.mst file inside another .mst file)
For example I have template.mst file with this code:
{{#comments}}
// Here I want to use another external .mst file
{{/comments}}
So I careated a comment.mst file beside the template.mst file and now I'm trying to use {{>comment}} to call this external template file - full example:
{{#comments}}
{{>comment}}
{{/comments}}
But it doesn't work. I tried to play with it a little bit, I tried to add the file extension {{>comment.mst}} and I tried to add the path {{>temmplates/comment}} and any pther option.
This is the code I use to load the template:
$.get('templates/template.mst', function(template) {
var rendered = Mustache.render(template, postData);
$('.inner-container').prepend(rendered);
});
I guess I missing something, Can someone give me an hint? Thanks!