3

I want to write a view that asks for some input then returns it as uppercase. I followed the instructions in Send Data from a textbox into Flask?.

The app is hosted using Phusion Passenger via cPanel at example.com/form. When I click Submit, I am sent to example.com. Nothing happens to the text on example.com/form before I am redirected.

What am I doing wrong? Why am I being redirected?

templates/form.html

<form action="." method="POST">
    <textarea name="text"></textarea>
    <input type="submit">
</form>

form.py

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/')
def form():
    return render_template('form.html')

@app.route('/', methods=['POST'])
def form_post():
    return request.form['text'].upper()
davidism
  • 121,510
  • 29
  • 395
  • 339
reynoldsnlp
  • 1,072
  • 1
  • 18
  • 45

1 Answers1

5

Both the answers you followed had an issue for apps that aren't hosted at the root. (They've been edited now.)

Your app is hosted at /form. A form's action should be an absolute path, not a relative path. Always use url_for to generate URLs and you'll avoid this issue.

<form action="{{ url_for('form_post') }}" method=post>

Since your two views share the same URL, the action can be omitted. A common pattern in this case is to use one view to handle GET and POST.

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        return request.form['text'].upper()

    return render_template('index.html')
davidism
  • 121,510
  • 29
  • 395
  • 339