html – Django and javascript – how to use the value of dropdown box to access the static image stored on server using the static tag-ThrowExceptions

Exception or error:
{% load static %}                                                         line 1
<html>                                                                    line 2
<head>                                                                    line 3
<meta charset="UTF-8">                                                    line 4
<select id="ddlViewBy">
<option value="Pranamasana.jpg">Pranamasana</option>
<img id='cat' crossorigin="anonymous" height = "620" width = "620"/>
<button onclick = "myfun()">button</button>
function myfun() {
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
document.getElementById("cat").src = "{% static 'Pranamasana.jpg' %}";        line 16  

Even though I have a drop down box I am hard coding the name of the image to be accessed in line 16.
I want to know the way if I can use the string ‘struser’ so that the image selected by user can be displayed without hard coding.

Any help would be appreciated and thanks in advance.

I am using django and this is a html page in my project

How to solve:

Django template executes your code before the javascript does so you can’t really use the javascript concatenate string adding. So the best way is to use {% get_static_prefix %}

var staticUrl = "{% get_static_prefix %}"
var strUsr = e.options[e.selectedIndex].value;
document.getElementById("cat").src = staticUrl + strUsr

Leave a Reply

Your email address will not be published. Required fields are marked *