atkat12 atkat12 - 1 year ago 243
Python Question

Flask: redirect(url_for()) returning html but not loading page

I am building a small web app in Flask, a code excerpt is below. Basically, I am trying to store some data in

and then move on to
once this is achieved. But
is not working.

When I run
, it displays
hello, world
in the console but the main page looks the same.

When I run
, it displays the html in the console but the main page looks the same.

Here is what I have:

@app.route('/startsession', methods=['POST'])
def startsession():
_username = request.form['inputName']
session['user_name'] = _username
return redirect(url_for('tagpage'))

Then, either:

### TEST 1
def tagpage():
return "hello, world"


### TEST 2
def tagpage():
return render_template('tagpage.html', filename=filename)

Sample of what I see after clicking the button that triggers

enter image description here

How can I get the browser to actually go to

Here is my JQuery script:

url: '/startsession',
type: 'POST',
data: $('form').serialize(),
success: function(response){
error: function(error){


Answer Source

I guess the screenshot shows the output of console.log and thus I conclude that the POST is done in javascript, probably jQuery (waiting for an answer from the asker).

If this is the case, this is the expected behavior. The POST is done and the javascript receives the redirect and GET's the redirected resource.

And the javascript is logging the html of the redirected resource.

If you want to redirect the browser you can either do this manually in the javascript (after the POST is done) using:

window.location = "/tagpage";

Or let the browser do it for you, in this case, the POST must be done through a <form>.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download