Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask POST request returning to main webpage instead of returning result

Tags:

python

flask

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()
like image 642
reynoldsnlp Avatar asked Dec 06 '25 07:12

reynoldsnlp


1 Answers

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')
like image 54
davidism Avatar answered Dec 07 '25 19:12

davidism



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!