Home > Software engineering >  Flask HTML Use button as input
Flask HTML Use button as input

Time:09-24

Context

I'm trying to find out how can I use the button in my page as an action to a function in my app.py with its respective value.

Currently I have this code as my app.py

@app.route('/')
def home():
    return render_template('home.html')

# For web app
@app.route('/search', methods=['POST'])
def search():
    user_input = [str(i) for i in request.form.values()]
    book_rec = search_result(user_input[0],search_define)

    return render_template('home.html',data=book_rec)

Which yields something like this if you fill the input form and click Find. I want to make the Recommendation button clickable and will trigger and action in my app.py enter image description here

Current Code

I generate the cards in the above picture with this html script, this is also my current html script I want to modify the button or form part. And as you can see, data is just a python dictionary.

    <center>
        <div >
        {% for i in data %}
            <div >
                <div >
                    <img src="{{data[i]['image_url_s']}}"  alt="...">
                    <h2 style="color: #000000;">{{data[i]['book_title']}}</h2>
                    <p style="color: #000000;">{{data[i]['book_author']}}</p>
                    <p style="color: #000000;">{{data[i]['year_of_publication']}}</p>
                    <form action="{{ url_for('rec')}}" method="post">
                        <button type="submit" ><strong>Recommendation</strong></button>
                    </form>
                </div>
            </div>
        {% endfor %}
    </center>

Now I'm trying to connect the Recommendation button to this part of lines in my app.py

@app.route('/rec')
def rec():
    #Use the {{data[i]['isbn_index']}} value from respective `Recommendation` button as an input
    #Do something
    #return something

Question

How should I setup my form or button in the HTML script so I can trigger /rec when I click on the Recommendation and use the respective isbn_index value as input?

CodePudding user response:

Inside the jinja for loop, you can use your index of loop or the value of 'i' to create a distinctive name for your button element. For example,

<button type="submit"  name="button_{{i}}"><strong>Recommendation</strong></button>

and then in your route, you can create conditional statements to look for each button, if it was pressed; do something different.

if request.method == "POST":
    for i in data:
        button_name = f'button_{i}'
        if button_name in request.form:
            # do something interesting
            print(f'I pressed this button: {button_name}')
  • Related