Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading