How call a function using onClick in a jinja/flask button

28 Views Asked by At

I have this route in main.py:

@app.route('/')
def home():
    
    def remove_book():
        print('im here')
    
    return render_template('index.html', books=Books.query.all(), rem_book=remove_book)

So, I try call the remove_book function in button of my index.html file:

<button class="btn btn-danger btn-sm" onclick={{rem_book}}>X</button>

And nothing is printed in terminal, whats wrong with my code?

I expected the 'im here' string printed on terminal

1

There are 1 best solutions below

0
efeakaroz13 On

You can create a form in HTML and make a post route like this: index.html

<form action="/" method="POST">
<button type="submit">click me</button>
</form>

app.py

from flask import Flask,render_template,request

def myfunc():
    for i in range(5):
        print("Hello world!")
    return 0

app = Flask(__name__)
@app.route("/",methods=["POST","GET"])
def index():
    if request.method == "POST":
        #this will where you will call your function
        myfunc()

        # visit form documentation https://tedboy.github.io/flask/generated/generated/flask.Request.html
        return """<script>alert("You've run the function!");window.location.assign('/')</script>""""
    return render_template("index.html")

I hope this solves your problem. But if you are making a function to change the DOM content(webpage), you need to learn JS.