Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to html input to Flask?

I have this html bit:

<form action='quiz_answers'>
    <p> Question1? </p>
    <input type="radio" name="q1" value="2">Answer1</input>
    <input type="radio" name="q1" value="1">Answer2</input>
    <input type="radio" name="q1" value="0">Answer3</input>
    <input type="radio" name="q1" value="0">Answer4</input>

    <p> Question2? </p>
    <input type="radio" name="q2" value="2">Answer1</input>
    <input type="radio" name="q2" value="1">Answer2</input>
    <input type="radio" name="q2" value="0">Answer3</input>
    <input type="radio" name="q2" value="0">Answer4</input>
</form>

and this python code:

from flask import Flask, render_template, request

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

@app.route('/quiz_answers', methods=['POST'])
def quiz_answers():
    q1 = request.form['q1']
    q2 = request.form['q2']
    q4 = request.form['q4']
    q5 = request.form['q5']

if __name__ == "__main__":
    app.debug = True
    app.run(host='0.0.0.0')

How would I go about adding making a button which, after it has been clicked on + question 1 and 2 have been answered, opens a new template with the results? So in short, how do I make a button saying "Yup, the questions have been answered, count the values and return them in a new HTML page"?

The Flask Quick Start tutorial does go trough HTTP requests but doesn't answer my quetion in this specific situation. Googling only yielded this stackoverflow thread which didn't bring me anywhere.

like image 926
user2374668 Avatar asked Oct 06 '13 19:10

user2374668


People also ask

Can I use HTML with Flask?

Flask uses the Jinja template engine to dynamically build HTML pages using familiar Python concepts such as variables, loops, lists, and so on.


1 Answers

You should be able to add a submit button to the form to POST or GET the data response back to the action.

In this case, you will probably want to modify your form tag definition to:

<form action="/quiz_answers" method="POST">

And add a submit button like this:

<input type="submit" value="Submit!" />

When the user clicks, it should generate a POST request back to http://your_server/quiz_answers.

like image 98
Michael Avatar answered Oct 13 '22 00:10

Michael