Forums

N00b can't get form processing with flask

Hi, I can't figure out why I keep getting error 500 when accessing the site with this code:

from flask import Flask, request

app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def a():
    return '<form method="post" action="/">What is your name? <input type="text" name="name"><input type="submit"></form><p>Your name is ' + request.form('name')

When you initially load the page, there is no form on the request, because the first GET request will only show the form. After you submit the form, the POST request will contain the form information that you are trying to access with request.form('name'). There is an example in the Flask documentation that shows the separation of the GET and the POST parts of the interaction here: https://flask.palletsprojects.com/en/1.1.x/quickstart/#http-methods

Also, when you get a 500 error, there will be tracebacks in your error and server logs that you can use to start debugging.

Yes, thanks, I figured it out. This works now:

from flask import Flask, request

app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def a():
    content = '<form method="post" action="/">What is your name? <input type="text" name="name"><input type="submit"></form>'
    if request.method == 'POST':
      content = content + '<p>Your name is ' + request.form['name']
    return content

Great! Glad to hear it.