Issue
i have seen two different ways of handling post requests on a route:
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
# insert logic on data
return render_template('register.html', title="Register", form=form)
and:
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
# insert logic
I cannot seem to find a clear answer to the following questions, and i cant seem to find a duplicate in SO:
- Do they refer to different use cases?
- Should both be used? Are they
redundant?
Thanks in advance!
Solution
Your first method will execute on either situation: "user requests the data [GET]" or "user posts a form [POST]". Use the second method if want to assign both the GET and POST requests to the same route.
See the code below :
if request.method == "POST":
# HTTP Method POST. That means the form was submitted by a user
# and we can find her filled out answers using the request.POST QueryDict
else:
# Normal GET Request (most likely).
# We should probably display the form, so it can be filled
# out by the user and submitted.
Or you will want to create different route function, one that will post your form and another that will redirect you to get function after you post your data if this is what you are looking for.
@app.route('/register', methods=['POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
# redirect to '/register_success' with user data
@app.route('/register_success',methods=['GET'])
def registration_success():
# render <You are registered 'user'> --etc--
Answered By – Nabin Paudel
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0