Solution 1 :

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>

Problem :

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?

Comments

Comment posted by gittert

shouldnt the form action be something like this: form action=”{{ url_for(‘process_number’) }}”

By