Forums

Automatically Redirecting When Post Is Called

Relevant Flask code:

@app.route('/test/<testvar>', methods=["POST", "GET"])
def testTheVar(testvar):
    if request.method == "POST":
        pass
    return render_template("test_page.html")

test_page.html: <html>

<head>
</head>
<body>
    <div class="container">
        <div class="row">
            <form action="." method="POST">
                <textarea class="form-control" name="move" placeholder="Enter Your Move Here"></textarea>
                <input type="submit" value="Submit Move">
            </form>
        </div>
    </div>
</body>

</html>

When I go to zswitten2.pythonanywhere.com/test/ttt, the page loads fine. But when I submit any text with the button, the page redirects to zswitten2.pythonanywhere.com/test/, and gives this error:

The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

Why is this redirect occurring? Thanks in advance.

what happens if you put your form action to be /test/ttt instead?

What do you mean by "form action"? Note: while the variable in the route has no purpose in this sample code, in my actual application it will.

I think Conrad was referring to the action property of the form tag.

However, I think I can see the problem. When you submit to ".", then you're not saying "submit to the current page". You're actually saying "submit to the 'directory' containing the current page". This is a subtle point; if the URL of the current page is /test/ttt/ then submitting to "." will submit to /test/ttt/. But if the URL of the current page is /test/ttt without the trailing slash, then the ttt is treated as if it's a filename, and the submission goes to /test/.

So, if you want the action property of the form tag to be "." (which is perfectly sensible) then you should make sure that there's a trailing slash in the URL to avoid it from posting to a different URL. The easiest way to do that is probably to add a trailing slash in your app.route, eg.

@app.route('/test/<testvar>/', methods=["POST", "GET"])

Giles, that worked. Thanks!

Out of curiosity, it sounds like you're saying there's an alternate solution where the action property of the form tag would be something else?

well you could also have made the form submit to '/test/ttt/' instead of '.', but that would be hard coding in the variable.

That's almost what I meant -- the alternative to using "." and putting a slash at the end of the URL would be to use the url_for function in the view or the template to generate a full URL, so the template served to the user would be something like /test/ttt but the variable would essentially be interpolated in rather than hard-coded.

But I think the solution that you have now, and that works, is probably the best one. If you view the source of this forum page and look at the form to add a new post, you'll see that that is exactly what we do here :-)