Reputation: 455
I have a login page as login.py
which renders login.html
. On submit i want to redirect to mainpage.py
which renders mainpage.html
. But on submit click it just doesn't redirect. I get a page not found error. And the url remains the same
@app.route('/login',methods = ['GET','POST'])
def index():
try:
if request.method =='POST':
db_user = request.form['db_user']
db_pwd = request.form['db_pwd']
if (connect(db_user,db_pwd)==1):
return redirect("/mainpage", code=302)
else:
return render_template('login.html')
except Exception as e:
print(("error :", str(e)))
return render_template('login.html')
What should be mentioned in the redirect option? is it the html filename or py filename where the html gets rendered? I tried with html filename,py filename and the name in the @app.route. but without success
Upvotes: 0
Views: 20763
Reputation: 3784
When you redirect to /mainpage
, Flask will be looking for a route handler in your login.py
file, not mainpage.py
. Since login.py
doesn't have a route handler for /mainpage
, it gives you a 404. It never reaches mainpage.py
.
What you are trying to do is separating your routes across different files. For that, you need to explicitly tell Flask where your route handlers are (in other words, in which files it should look for route handlers).
There are two ways for doing that:
See this documentation (Larger Applications) to learn how to organize your files as a package. You'll have to import mainpage.py into login.py, or vice-versa.
Or use a blueprint: Modular Applications with Blueprints.
Please note that you'll only need that if your application has a substantial size. If you have just a few route handlers, you should probably keep it simple with everything in one single file.
Upvotes: 3
Reputation: 6485
The first parameter of redirect
is the url which you want the client redirected to. You can hard code the url as the first parameter. And also you can use url_for
to generate the url for the given endpoint.
For example:
@app.route("/url")
def endpoint():
return "Test redirect & url_for"
You can use redirect(url_for("endpoint"))
or redirect("/url")
to redirect to /url
And the Quickstart point the advantages of use url_for
instead of hard code the url.
Upvotes: 1