0

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);
};
6
  • You can't do that. What you can do in javascript is create a fetch request to your view that has the response "Hellow World" Commented Nov 12, 2021 at 2:24
  • Using the "fetch ... .then" syntax? Commented Nov 12, 2021 at 2:28
  • Yes, that's basically for calling URLs in javascript. Commented Nov 12, 2021 at 2:29
  • Okay, so I would fetch the view url and in the .then block I would call the Python function? Commented Nov 12, 2021 at 2:36
  • The URL is the python view function, the then block contains the response of your view which would be "Hello World" Commented Nov 12, 2021 at 2:37

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.