Last Updated : 23 Jul, 2025
This article covers adding users and displaying their usernames in Flask. After login, users are redirected to a profile page with a welcome message. User data is stored in MySQL for easy management via phpMyAdmin.
Creating Templates for User InterfaceWe need three HTML files inside a templates folder:
This page includes fields for username, email, and password. Once submitted, it stores the data in the MySQL database and flashes a success message.
HTML
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>User Registration Form</title>
</head>
<style>
.hi{
color: green;
}
.ok{
display: block;
margin-left: 80px;
margin-top: -15px;
border: 1px solid black;
}
.gfg{
margin-left: 30px;
font-weight: bold;
}
.gf{
margin-left: 10px;
font-weight: bold;
}
.btn{
margin-top: 20px;
width: 80px;
height: 25px;
background-color: orangered;
color: white;
}
.y{
color: gray;
}
</style>
<body>
<div class="container">
<h2 class="hi" > GFG User Registration </h2>
<h4 class="y" >Note : fill following details !</h4>
<form action="{{ url_for('register') }}" method="post">
{% if message is defined and message %}
<div class="alert alert-warning"> <strong> {{ message }} ???? </strong></div>
{% endif %}
<br>
<div class="form-group">
<label class="gfg">Name:</label>
<input class="ok" type="text" class="form-control" id="name" name="name" placeholder="Enter name" name="name">
</div>
<div class="form-group">
<label class="gfg">Email:</label>
<input class="ok" type="email" class="form-control" id="email" name="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label class="gf">Password:</label>
<input class="ok" type="password" class="form-control" id="password" name="password" placeholder="Enter password" name="pswd">
</div>
<button class="btn" type="submit" class="btn btn-primary">Register</button>
<p class="bottom">Already have an account? <a class="bottom" href="{{url_for('login')}}"> Login here</a></p>
</form>
</div>
</body>
</html>
Output:
User Registration page login.htmlThis page allows registered users to log in using their email and password. Upon successful login, they will be redirected to the user profile page.
HTML
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>User Login Form</title>
</head>
<style>
.gfg{
display: block;
margin-left: 70px;
margin-top: -15px;
}
.ok{
margin-left: 20px;
font-weight: bold;
}
.btn{
margin-top: 20px;
width: 80px;
height: 25px;
background-color: gray;
color: white;
}
.user{
color: green;
}
</style>
<body>
<div class="container">
<h2 class="user"> GFG User Login</h2>
<form action="{{ url_for('login') }}" method="post">
{% if message is defined and message %}
<div class="alert alert-warning"> <strong> {{ message }} ????</strong></div>
{% endif %}
<br>
<div class="form-group">
<label class="ok">Email:</label>
<input class="gfg" type="email" class="form-control" id="email" name="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label class="pop"> <strong> Password:</strong></label>
<input class="gfg" type="password" class="form-control" id="password" name="password" placeholder="Enter password" name="pswd">
</div>
<button class="btn" type="submit" class="btn btn-primary">Login</button>
<p class="bottom">Don't have an account? <a class="bottom" href="{{url_for('register')}}"> Register here</a></p>
</form>
</div>
</body>
</html>
Output:
Login page user.htmlDisplays the logged-in username and provides a logout button.
HTML
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>User Account</title>
</head>
<style>
.gfg{
font-size: 25px;
color: red;
font-style: italic;
}
</style>
<body>
<div class="container">
<div class="row">
<h2>User Profile</h2>
</div>
<br>
<div class="row">
Logged in : <strong class="gfg"> {{ session['name'] }} </strong>| <a href="{{ url_for('logout') }}"> Logout</a>
</div>
<br><br>
<div class="row">
<h2>Welcome to the User profile page...</h2>
</div>
</div>
</body>
</html>
Output:
User Page Creating DatabaseMake sure MySQL is installed on your system, if it is not, refer to Setting up MySQL. Log in to MYSQL server from terminal and create database - "user_table" by using commmand -
CREATE DATABASE user_table;
This command will create the database and the user table will be created from the flask app code.
Implementing Flask Application Step 1: Import all libraryTo set up a Flask application with MySQL for admin login, we start by writing the Python code in app.py. This file handles imports, database connections, and authentication. Here’s the process:
Python
# Import all important libraries
from flask import *
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re
# initialize first flask
app = Flask(__name__)
app.secret_key = 'GeeksForGeeks'
# Set MySQL data
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = '' # Enter your password
app.config['MYSQL_DB'] = 'user-table'
mysql = MySQL(app)
Code Breakdown:
Create a login() function to handle user authentication and session management. This function interacts with MySQL to verify user credentials. Here's how it works:
Python
# Make login function for login and also make
# session for login and registration system
# and also fetch the data from MySQL
@app.route('/')
@app.route('/login', methods=['GET', 'POST'])
def login():
message = ''
if request.method == 'POST' and 'email' in
request.form and 'password' in request.form:
email = request.form['email']
password = request.form['password']
cursor = mysql.connection.cursor
(MySQLdb.cursors.DictCursor)
cursor.execute(
'SELECT * FROM user WHERE email = % s AND password = % s',
(email, password, ))
user = cursor.fetchone()
if user:
session['loggedin'] = True
session['userid'] = user['userid']
session['name'] = user['name']
session['email'] = user['email']
message = 'Logged in successfully !'
return render_template('user.html',
message=message)
else:
message = 'Please enter correct email / password !'
return render_template('login.html', message=message)
# Make function for logout session
@app.route('/logout')
def logout():
session.pop('loggedin', None)
session.pop('userid', None)
session.pop('email', None)
return redirect(url_for('login'))
Code Breakdown:
On the login screen, users can log in using their email and password. The system also includes flash messages for better user feedback. Here's how it works:
Python
# Make a register session for registration
# session and also connect to Mysql to code for access
# login and for completing our login
# session and making some flashing massage for error
@app.route('/register', methods=['GET', 'POST'])
def register():
message = ''
if request.method == 'POST' and 'name' in
request.form and 'password' in request.form
and 'email' in request.form:
userName = request.form['name']
password = request.form['password']
email = request.form['email']
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM user WHERE email = % s',
(email, ))
account = cursor.fetchone()
if account:
message = 'Account already exists !'
elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
message = 'Invalid email address !'
elif not userName or not password or not email:
message = 'Please fill out the form !'
else:
cursor.execute(
'INSERT INTO user VALUES (NULL, % s, % s, % s)',
(userName, email, password, ))
mysql.connection.commit()
message = 'You have successfully registered !'
elif request.method == 'POST':
message = 'Please fill out the form !'
return render_template('register.html', message=message)
Code Breakdown:
from flask import *
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re
# initialize first flask
app = Flask(__name__)
app.secret_key = 'GeeksForGeeks'
# Set MySQL data
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = '________' # Use you mysql password
app.config['MYSQL_DB'] = 'user_table'
mysql = MySQL(app)
def create_table():
cursor = mysql.connection.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS user (
userid INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
)
""")
mysql.connection.commit()
cursor.close()
# Call the function when the app starts
with app.app_context():
create_table()
@app.route('/')
@app.route('/login', methods=['GET', 'POST'])
def login():
message = ''
if request.method == 'POST' and 'email' in request.form and 'password' in request.form:
email = request.form['email']
password = request.form['password']
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute(
'SELECT * FROM user WHERE email = % s AND password = % s',
(email, password, ))
user = cursor.fetchone()
if user:
session['loggedin'] = True
session['userid'] = user['userid']
session['name'] = user['name']
session['email'] = user['email']
message = 'Logged in successfully !'
return render_template('user.html',
message=message)
else:
message = 'Please enter correct email / password !'
return render_template('login.html',
message=message)
# Make function for logout session
@app.route('/logout')
def logout():
session.pop('loggedin', None)
session.pop('userid', None)
session.pop('email', None)
return redirect(url_for('login'))
@app.route('/register', methods=['GET', 'POST'])
def register():
message = ''
if request.method == 'POST' and 'name' in request.form and 'password' in request.form and 'email' in request.form:
userName = request.form['name']
password = request.form['password']
email = request.form['email']
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM user WHERE email = % s', (email, ))
account = cursor.fetchone()
if account:
message = 'Account already exists !'
elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
message = 'Invalid email address !'
elif not userName or not password or not email:
message = 'Please fill out the form !'
else:
cursor.execute(
'INSERT INTO user VALUES (NULL, % s, % s, % s)',
(userName, email, password, ))
mysql.connection.commit()
message = 'You have successfully registered !'
elif request.method == 'POST':
message = 'Please fill out the form !'
return render_template('register.html', message=message)
# run code in debug mode
if __name__ == "__main__":
app.run(debug=True)
After writing the whole code open your terminal and run the following command
Outputpython app.py
Run the flask app using "python app.py" command. The snapshot of the home page is already provided above, we will navigate to the register page and fill out the form, below is the snapshot:
Registration pageAfter filling up the registration form and clicking the "Register" button, we will get a registration successfull page like below:
Registration SuccessfullLet's try to log in using the credentials we just registered with:
Login PageAfter successfully logging in, we will see the username page:
User PageRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4