1

I am using flask to develop a website and now i encountered a problem. I am thinking whether I can pass a "WTF form" object in flask. Like,

@app.route('/') @app.route('/index') @login_required def index(): user = flask.g.user form = PostForm() return flask.render_template("index.html", title="Home", user=user, form = form) 

This form, an instance of PostForm, actually will be processed by the following code:

@app.route('/note/<int:id>', methods=['POST']) def note(id): form = ?(how to get this form?)? if form.validate_on_submit(): print id content = form.body.data currentTime = time.strftime('%Y-%m-%d', time.localtime(time.time()) ) user_id = id return flask.redirect(flask.url_for('login')) return flask.redirect( flask.request.args.get('next') or flask.url_for('index') ) 

In the template, I set the action to be "/note/1", so it will forward to this address. But the question, how can I get the form created in the function index?

I have tried to use flask.g (Obviously, it does not work because it's another request). And I also tried to use global variable. It failed, either.

Could anyone give me a solution or any advice?

Thank you in advance!

1 Answer 1

1

You simply need to construct a new version of PostForm in your note route and use the posted data in request.form:

from flask import request @app.route('/note/<int:id>', methods=['POST']) def note(id): form = PostForm(request.form) # or, if you are using Flask-WTF # you can do # form = PostForm() # and Flask-WTF will automatically pull from request.form 
Sign up to request clarification or add additional context in comments.

3 Comments

You don't even need the request.form argument if you're using Flask-WTF, it's automatically populated as a convenience.
Thank you so much! It seems like I am still not familiar with the flask and its extensions.
Do u mean i can just do form = PostForm()? I don't this is gonna work. Because I tried this way before.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.