[Answered ]-Call a dynamic python function after the webpage is loaded in Django

2đź‘Ť

âś…

Sounds like you have to use AJAX for this. You can define a Django view which returns a JSON message with something like:

{
    status: "ok",
    url: "img1.jpg"
}

So in your code, you can define an event handler (in JavaScript) with something like this:

// Attach a listener to a button for a click event,
document.getElementById("testImageButton").addEventListener("click", function() {
    var xhr = new XMLHttpRequest();
    // This URL returns the above JSON.
    xhr.open("GET", "/images/random"); 
    xhr.onloadend = function() {
         // Should have error handling in case response does not return correctly.
         var imageResult = JSON.parse(xhr.response);
         if(imageResult['status'] == 'ok') {
             // update the image src
             document.getElementById("testImage").setAttribute("src", imageResult['url']);
         }
    }
    xhr.send()
})

So the only “dynamic function part” is whatever is inside your Django view function.

Leave a comment