0

I am using flask and wtforms. When a user clicks a submit button for the form, I want to pop up a message saying that the submission succeeded. For that I have a parameter for my flask route with a default value of False. When the user submits, I want it to be true, so when it re-renders the page, it knows to show the user the extra bit saying "Success". However the parameter always seems to be false. My python looks like,

@app.route('/myPage', methods=['GET', 'POST'])
def myPage(success=False):
    print success

    form = MyForm()
    if form.validate_on_submit():
        print "did validate"
        return redirect(url_for('myPage', success=True))

    return render_template('/MyPage.html', form=form, success=success)

And my html looks like,

...
{% if success %}
    <div class="alert alert-success alert-dismissable">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> User added
    </div>
{% endif %}
...
<form method="POST" action="{{ url_for('register', success=True) }}">
...

In both my python and html redirects, I try setting success to be true, but no combination of those seem to work. When I "print success", it always says that it is false. Any ideas?

1 Answer 1

1

Flask binds method parameters to route arguments if they a part of the route. See documentation.

Try:

@app.route('/mypage/<int:success>', defaults={'success': 0})
def my_page(success):
   ...

This would cause url_for to build a URL like /mypage/1 or /mypage/True, which is probably not what you want.

If you want to use a querystring parameter, you should manually get it from the request:

@app.route('/mypage/')
def my_page():
  success = request.args.get('success', False)
  ...

url_for('my_page', success=True) would now generate something like /mypage/?success=True because:

Variable arguments that are unknown to the target endpoint are appended to the generated URL as query arguments.

(from the url_for docs)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, I used the "success = request.args.get('success', False)" method, and it works like a charm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.