How to get form data from input as variable in Flask?

北城余情 提交于 2019-12-01 14:41:52

You are trying to generate a url based on user input, but user input isn't available when Jinja is rendering the template on the server side, it's only available on the client side. So if you wanted to post to URLs with the game id as a URL parameter, you would have to build that URL on the client side with JavaScript.

For what you're trying to do, that's not really necessary. You can get the submitted value of a named input with request.form['name']. Buttons are just like any other input, so you can name them to find out what action was taken.

@app.route('/manage_game', methods=['POST'])
def manage_game():
    start = request.form['action'] == 'Start'
    game_id = request.form['game_id']

    if start:
        start_game(game_id)
    else:
        stop_game(game_id)

    return redirect(url_for('index'))
<form method="POST">
    <input type="text" name="game_id"/>
    <input type="submit" name="action" value="Start"/>
    <input type="submit" name="action" value="Stop"/>
</form>

Even that's more verbose than you need. Given that you'd know if a game was already in progress, just toggle the current status instead of picking an action. It would never make sense to start a game that's already started, only stop it.

I cannot comment, but I would like to correct davidism's code. I believe that you need action within your form element with a value which corresponds to the function within the server python code for this to work. Minor, but an important correction. So it would be like this:

In your server.py:

@app.route('/manage_game', methods=['POST'])
    def manage_game():
    start = request.form['action'] == 'Start'
    game_id = request.form['game_id']

    if start:
        start_game(game_id)
    else:
        stop_game(game_id)
    return redirect(url_for('index'))

In your HTML:

<form method="POST" action=/manage_game>
    <input type="text" name="game_id"/>
    <input type="submit" name="action" value="Start"/>
    <input type="submit" name="action" value="Stop"/>
</form>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!