miguelgrinberg / flasky

Companion code to my O'Reilly book "Flask Web Development", second edition.
MIT License
8.54k stars 4.21k forks source link

Flask-WTF Question #553

Closed samuelerickson977 closed 1 year ago

samuelerickson977 commented 1 year ago

Please do git checkout 4a and look at line 33 in hello.py. Can you explain to me why instantiating the NameForm object after every request does not overwrite the state of the form from the POST request? For example, I navigate to /, and then enter my name and click submit. When I click submit, the POST request uses the index() function. However, if index() is called, then won't the form object just the POST request lose it's data because a new NameForm object is instantiated?

miguelgrinberg commented 1 year ago

No, that's not how Flask-WTF works. When you create the NameForm class Flask-WTF looks in the request object from Flask to see if data for the form has been submitted in the current request. If yes, it loads the data into the newly created form object. If not it creates the form object without data. The form data is not persisted anywhere, you have to save it (or use it somehow) before the request that handles the form submission ends.

samuelerickson977 commented 1 year ago

OK, that makes more sense. Thank you very much sir.

On Tue, Jul 18, 2023 at 1:09 PM Miguel Grinberg @.***> wrote:

No, that's not how Flask-WTF works. When you create the NameForm class Flask-WTF looks in the request object from Flask to see if data for the form has been submitted in the current request. If yes, it loads the data into the newly created form object. If not it creates the form object without data. The form data is not persisted anywhere, you have to save it (or use it somehow) before the request that handles the form submission ends.

— Reply to this email directly, view it on GitHub https://github.com/miguelgrinberg/flasky/issues/553#issuecomment-1640711047, or unsubscribe https://github.com/notifications/unsubscribe-auth/BBA5AMHCOICENYAV54IWCZTXQ3GMTANCNFSM6AAAAAA2OUKOTA . You are receiving this because you authored the thread.Message ID: @.***>