I am very new to Flask and have been trying to use it for a school project. I've had some help to start off with but i'm stuck now due to an error message received when inputting a username and password to log in. My code for the application is
@app.route("/loginuser")
def loginpage():
return render_template("login.html")
@app.route("/login", methods=['GET','POST'])
def login():
if request.method == 'POST':
# Save the form data to the session object
username = request.form['username']
password = request.form['password']
success, message, name = checklogin(username, password)
if success:
session['username'] = name
return redirect('/balance')
else:
return message
return """
<form method="post">
<head>
<title>
Login
</title>
<style>
h1 {
text-align: center;
}
</style>
</head>
<body>
<h1>Please Login</h1>
<table border="1" align="center">
<tr><td>Login</td><td><input type="text" class="btLoginButton"></td></tr>
<tr><td>Password</td><td><input type="password"></td></tr>
<tr><td></td><td><input type="submit" value="login" class="btLoginButton"></td></tr>
</table>
</body>
</form>
"""
and my html
{% extends 'mastertemplate.html' %}
{% block title %}Login Page{% endblock %}
{% block content %}
<head>
<title>
Login
</title>
<style>
h1 {
text-align: center;
}
</style>
</head>
<body>
<h1>Please Login</h1>
<table border="1" align="center">
<tr><td>Login</td><td><input type="text" class="btLoginButton"></td></tr>
<tr><td>Password</td><td><input type="password"></td></tr>
<tr><td></td><td><input type="submit" value="login" class="btLoginButton"></td></tr>
</table>
</body>
{% endblock %}
I think i've figured out the error arises due to the
username = request.form['username']
password = request.form['password']
as I know it occurs in the POST part and I've done some debugging. Since I am very new to flask I have no clue why there's an error or how I can fix it. Any advice/help is apprecitaed.
You forgot to assign a name attribute for the input fields. For this reason the dict with the form data is empty and the key cannot be found. The error message appears.
The form data can be requested using the name of the input field.
<input type="text" name="username" />
username = request.form['username']