0

I am new to django.

What i am trying to do is to run a django function from my "main.py" file when a html button is pressed.

what I've done is created a button in html:

<input type="button" value="Formatting excel" onclick="excel_formatting">

And then in my "main.py " I have:

def excel_formatting():
print("hello world")
return()

The website loads fine, but when i press the button nothing is printed in the terminal. i must be doing something wrong.

Kitchen
  • 73
  • 1
  • 2
  • 7
  • Python functions run server-side, for the reason that you can't call the way you are doing it, if you really want to use them you have to use a url that executes that function or via json – cosmos multi Jan 18 '21 at 20:50
  • A Web application comes with two different sides: Frontend and Backend. Django runs on the server-side (backend) so python codes are only callable on python codes. But HTML, CSS, and javascript are languages used on the client-side (Frontend). So is it possible to call some Python code from your HTML, answer is no but is it possible to call it from your frontend code via APIS. APIs like formdata, json, and many available options. I suggest you learn HTML forms and JSON APIs. – Navid Nabavi Jan 19 '21 at 08:28

1 Answers1

0

you can have a button that is a link and when the user presses the button it will redirect them to the link which will activate the function.

views.py

def button(request):
   print('hello')

urls.py

from . import views as main_views
path('button/', main_views.button, name="button"),

index.html

<a href="{% url 'button' %}" class="btn btn-primary">Button</button>
brian yeap
  • 62
  • 1
  • 6