Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

python - The correct use of method post-get in flask in select form

I try to use select method in html with flask. My code is

from flask import Flask, render_template, request
import psycopg2
import numpy as np

d = [10,12,16,17]

@app.route('/demo_html', methods=['GET', 'POST'])
def process_number():
    selected_number = ''
    if request.method == 'POST':
        selected_number = request.form['number']

    return render_template('demo_html.html', d=d, length=len(d),selected_number=selected_number)

This is my html file

demo_html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="" method="POST">
        <select>
        {% for i in range(length)  %}
            <option name="number">change number {{d[i]}}</option>
        {% endfor %}
        </select>
        <input type="submit">


    </form>
    <p>you selected number  {{ selected_number }}</p>

</body>
</html>

At the second step I get the following error: Bad Request The browser (or proxy) sent a request that this server could not understand.

The question: How do I render the template successfully using the post method?

question from:https://stackoverflow.com/questions/65626138/the-correct-use-of-method-post-get-in-flask-in-select-form

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should try running the Flask app in debug mode:

app.run(host='127.0.0.1', port=5000, debug=True)

That will give you a more detailed error message:

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'number'

This indicates that there is no form item with the name number in the submitted form. Looking at your HTML form, it looks like the name attribute has been misplaced; you also need it in the select element. This HTML form fixes the error:

<form action="#" method="POST">
    <select name="number">
    {% for i in range(length)  %}
        <option name="number">change number {{d[i]}}</option>
    {% endfor %}
    </select>
    <input type="submit">
</form>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...