In flask should I ever redirect to the same route? FWIW the code below is the register route. Also does flash messages work before redirects or render_template ?
Just to confirm, I think I can redirect to another route or render_template without causing any errors. Is this correct?
Here is an example where I think why redirects to the same routes will cause an error.
I am using wtf forms. In wtf forms I have a username email password confirmation_password for the register routes forms.
@userinfo.route("/register", methods = ['POST', 'GET'])
def register():
form = RegistrationForm()
# if the value other then None, iow's you have a username in the database
# The try is used if the database table User is empty.
if form.validate_on_submit():
try:
all_usernames = User.query.filter_by(username=form.username.data).all()
flash ("The usesrname is already taken. Please select another username.")
except:
all_usernames = None
finally:
# do I want to redirect to register route?
if all_usernames == forms_username:
return redirect(url_for('userinfo.register'))
return render_template("register.html", title=register, form=form)
I can show the html but I don't think it is needed Thanks.
Summary of browser steps.
step 1) I call the register function
step 2) Its starts off as a GET request and runs render_template because it skips form.validate_on_submit(). The register.html then runs.
step 3) I fill the information in the forms which username etc.
step 4) The POST request starts. This causes form.validate_on_submit() to run and all the code in between to run. Then instead of render_template I should redirect to a route. When I redirect I should get a GET request.
CodePudding user response:
Redirecting to the same route should not cause any problems.
But you need to know when to redirect to the same route. Redirecting to the same route after a POST request removes any data from the previous request. For example: if a user submitted a form and you want to show him a validation error you will not be able to, in this case you need to use render_tempate()
instead.
In you example you will use redirect()
if the registration was successful and there is not validation error, otherwise use render_tempate()