Reputation: 277
When i want to check if form data was submitted using POST
, what is the difference between:
if request.method == 'POST'
And:
if form.validate_on_submit():
?
Upvotes: 1
Views: 880
Reputation: 62
form.validate_on_submit()
does what the request.method == 'POST'
and more, so it's like a more advanced function.
form.validate_on_submit()
is a function implemented in the "Flask-WTF" package, which is a shortcut to two functions: form.is_submitted()
and form.validate()
def validate_on_submit(self):
"""Call :meth:`validate` only if the form is submitted.
This is a shortcut for ``form.is_submitted() and form.validate()``.
"""
return self.is_submitted() and self.validate()
Note: The self.validate()
is implemented by the "wtforms" package, which "Flask-WTF" uses the wtforms.Form
as a base class for the flask_wtf.FlaskForm
or the flask_wtf.Form
which is deprecated.
Going deeper, what the self.is_submitted()
function does is return a _is_submitted()
boolean function:
def is_submitted(self):
"""Consider the form submitted if there is an active request and
the method is ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
"""
return _is_submitted()
And the _is_submitted()
is defined as:
def _is_submitted():
"""Consider the form submitted if there is an active request and
the method is ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
"""
return bool(request) and request.method in SUBMIT_METHODS
The SUBMIT_METHODS
constant is defined this way:
SUBMIT_METHODS = set(('POST', 'PUT', 'PATCH', 'DELETE'))
From the snippets, you can see that the form.validate_on_submit()
handles the request.method
and does more.
So if you are making use of the Flask-WTF package and your form is inheriting from the "FlaskForm" class, it's better to use form.validate_on_submit()
than request.method == 'POST'
, as the former handles both verifying if a form is submitted and if the post request made is also valid.
Upvotes: 1