catching a form with Flask (very basic case)
<p>I want to use a very simple form to post comments to a Flask server.</p>

<p>My index.html is:</p>

<pre><code>&lt;form method="post" enctype="text/plain"&gt;
    Name:&lt;br&gt;
    &lt;input type="text" name="id"&gt; &lt;br&gt;
    Comment:&lt;br&gt;
    &lt;input type="text" name="comment"&gt; &lt;br&gt;
    &lt;input type="submit" value="Submit"&gt;
&lt;/form&gt;
</code></pre>

<p>The Flask app is:</p>

<pre><code>@app.route("/", methods=['GET', 'POST'])
def index():
    if (request.method == 'POST'):
        try:
            print (request.form['id'])
            print (request.form['comment'])
        except KeyError: 
            print('KeyError')
    return render_template('index.html')

app.run(host= '0.0.0.0')
</code></pre>

<p>I expect it to print the content of the form fields on the prompt output, but actually it prints "KeyError".
Where is the problem ?</p>

<p>You're getting a KeyError there because <code>request.form</code> is a <a href="http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.MultiDict" rel="nofollow"><code>ImmutableMultiDict</code></a> and a descendant of a python <code>dict</code>. You get <code>KeyError</code> raised when you try to access a key that doesn't exist.</p>

<p>This is happening because the key names you're trying to get don't match the HTML you've posted. You need to use the same field name you've entered in the HTML, so <code>nom</code> should be <code>id</code> and <code>remarks</code> should be <code>comment</code>?</p>

<p>But still you'll find that the snippet doesn't work. </p>

<p>This is because specifying <code>enctype="text/plain"</code> will prevent flask from parsing the POST'ed form-data into <code>request.form</code> as that is not a valid encoding for form submissions. See <a href="https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4" rel="nofollow">here</a>. Usually not setting <code>enctype</code> (or setting it to <code>application/x-www-form-urlencoded</code>) will suffice unless you have binary content or large sized payloads (usually file uploads) - if so set it to <code>multipart/form-data</code>.</p>

python html forms flask