Access Django variable from JavaScript variable


First of all, I will like to say this is my first question here! (pardon me if this is redundant or duplicated)

I am having some problems with calling JS scripts from Django template:

{% for suggestion in suggestions %}
    <img class="catalogue-poster" src="{{ suggestion.poster }}" alt="Portada"  onclick="                 
        document.getElementById('{{form.title.auto_id}}').value = '{{suggestion.title}}'
        document.getElementById('{{form.year.auto_id}}').value = '{{suggestion.year}}'
        document.getElementById('{{form.director.auto_id}}').value = '{{suggestion.director}}'
        document.getElementById('{{form.rating.auto_id}}').value = '{{suggestion.rating}}'
        document.getElementById('{{form.poster.auto_id}}').value = '{{suggestion.poster}}'
        document.getElementById('{{form.trailer.auto_id}}').value = '{{suggestion.trailer}}'
        document.getElementById('{{form.synopsis.auto_id}}').value = '{{suggestion.synopsis}}'
        document.getElementById('{{form.cast.auto_id}}').value = '{{suggestion.cast}}'  
    " />
{% endfor %}

So, first of all, how can I declare a function outside. I’m a C developer, sorry for my ignorance.

I’ve tried to create a script outside, such as

    function foo() {

And invoke it this way:

<img class="catalogue-poster" src="{{ suggestion.poster }}" alt="Portada"  onclick="foo()"/>  

But this simple thing that works on pure HTML, with django templates does not seem to work…

On the other hand, the real question was, is there a way to access a Django variable passed in render with a js variable?

Such as:

const jsVariable = 'title';
document.getElementById('{{form.jsVariable.auto_id}}').value = '{{suggestion.jsVariable}}'

I have not found any way to accomplish this, maybe there is another great idea!


I have tried one example. where is send a variable from python script and access its value in JavaScript

1) In

from django.shortcuts import render

def home_view(request):
    var_name = 'hello'
    return render(request, 'home.html', {'var_name':var_name})

2) In html file(home.html)

    <h1>Home Page</h1>
    <input type="button" value="Submit" onclick="fun()">

        function fun(){
            console.log('hello world '+ '{{var_name}}' );
        var temp = '{{var_name}}';
        console.log(temp + 20);

If i click submit button ( hello world hello ) is printed in console.

I stored value of var_name in temp which can be further used.

Answered By – SahilDesai

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published