Home > Net >  How to call a Python function with vanilla Javascript in a Django app
How to call a Python function with vanilla Javascript in a Django app

Time:11-12

I am working on a Django app and I am trying to call a Python function in views.py on a button click. I am trying to call this function using vanilla JavaScript if possible, because I am very unfamiliar with JavaScript and would like to try to keep things simple. The idea would be to display the text returned by the hello() function by using JavaScript to create a new div after the button is clicked. I believe I can do that part, but I have not been able to find any information on calling the Python function. I have the JavaScript function alerting with the text for now. Here is a sample of my code so far:

./views.py

def hello():
  return "Hello world"

./static/js/index.js

document.getElementById('button').addEventListener('click', printHello);

function printHello() {
  var text = // call Python function
  alert(text);
};

CodePudding user response:

It's as simple as this.

views.py

def hello():
    return "Hello World"

urls.py

urlpatterns = [
    path('Hello/', views.hello, name='hello')
]

javascript

fetch('http://localhost:3000/Hello')
  .then(data => console.log(data)); //Hello World
  • Related