In this tutorial we will write simple flask app that will show user profile by user name for example example.com/username
Also here user can create a new account . Its a simple, also we will explore the features of temples. So we will be able to generate html dynamically.
Lets begin
First make our project structure. In our website.
- User can create account.
- User can view other users account.
- And Every user will have unique username
Starting with simplicity
Our Predefined User Parrot, Cat, Rooster . For simplicity we stored this data in a python dictionary
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
users = {
'parrot': {
'name': 'Parrot',
'age': 5,
'workplace': 'Tropical Forest',
'favorite_food': 'Sunflower seeds',
'favorite_place': 'Jungle canopy',
'latest_post': 'Squawk!',
'friends': ['dog', 'cat']
},
'dog': {
'name': 'Dog',
'age': 3,
'workplace': 'Backyard',
'favorite_food': 'Bones',
'favorite_place': 'Dog park',
'latest_post': 'Woof!',
'friends': ['cat']
},
'cat': {
'name': 'Cat',
'age': 2,
'workplace': 'Living room',
'favorite_food': 'Fish',
'favorite_place': 'Sunny spot',
'latest_post': 'Meow!',
'friends': ['dog', 'parrot']
},
'rooster': {
'name': 'Rooster',
'age': 1,
'workplace': 'Farmyard',
'favorite_food': 'Grains',
'favorite_place': 'Chicken coop',
'latest_post': 'Cock-a-doodle-doo!',
'friends': []
}
}
@app.route('/')
def index():
return render_template('index.html', users=users)
In the index or landing page We will show the user list with the user profile link
And we will pass in the user list in the index template
Our template : index.html which located in the templates folder (templates/index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Profiles</title>
</head>
<body>
<h1>User Profiles</h1>
<ul>
{% for username, user in users.items() %}
<li><a href="{{ url_for('show_profile', username=username) }}">{{ user.name }}</a></li>
{% endfor %}
</ul>
</body>
</html>
Set unique route for user
@app.route('/<username>')
def show_profile(username):
if username in users:
user = users[username]
return render_template('profile.html', user=user)
else:
return "User not found", 404
We are using for loop to get the users names in the template
{% for username, user in users.items() %}
<li><a href="{{ url_for('show_profile', username=username) }}">{{ user.name }}</a
</li>
{% endfor %}
from flask import Flask, render_template
app = Flask(__name__)
users = {
'parrot': {
'name': 'Parrot',
'age': 5,
'workplace': 'Tropical Forest',
'favorite_food': 'Sunflower seeds',
'favorite_place': 'Jungle canopy',
'latest_post': 'Squawk!',
'friends': ['dog', 'cat']
},
'dog': {
'name': 'Dog',
'age': 3,
'workplace': 'Backyard',
'favorite_food': 'Bones',
'favorite_place': 'Dog park',
'latest_post': 'Woof!',
'friends': ['cat']
},
'cat': {
'name': 'Cat',
'age': 2,
'workplace': 'Living room',
'favorite_food': 'Fish',
'favorite_place': 'Sunny spot',
'latest_post': 'Meow!',
'friends': ['dog', 'parrot']
},
'rooster': {
'name': 'Rooster',
'age': 1,
'workplace': 'Farmyard',
'favorite_food': 'Grains',
'favorite_place': 'Chicken coop',
'latest_post': 'Cock-a-doodle-doo!',
'friends': []
}
}
@app.route('/')
def index():
return render_template('index.html', users=users)
@app.route('/<username>')
def show_profile(username):
if username in users:
user = users[username]
return render_template('profile.html', user=user)
else:
return "User not found", 404
if __name__ == '__main__':
app.run(debug=True)
Our profile.html in this template we just place the users profile with the value from users dictionary.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ user.name }}'s Profile</title>
</head>
<body>
<h1>{{ user.name }}'s Profile</h1>
<ul>
<li>User Name: {{ user.name }}</li>
<li>User Age: {{ user.age }}</li>
<li>Workplace: {{ user.workplace }}</li>
<li>Favorite Food: {{ user.favorite_food }}</li>
<li>Favorite Place: {{ user.favorite_place }}</li>
<li>Latest Post: {{ user.latest_post }}</li>
</ul>
{% if user.friends %}
<h2>Friend List</h2>
<ul>
{% for friend in user.friends %}
<li>{{ friend }}</li>
{% endfor %}
</ul>
{% else %}
<p>No friends yet!</p>
{% endif %}
</body>
</html>
In the code user can check the existing users profile. Now we will give the user freedom to create new users profile…..
@app.route('/create_profile', methods=['GET', 'POST'])
def create_profile():
if request.method == 'POST':
username = request.form['username']
if username not in users:
users[username] = {
'name': request.form['name'],
'age': int(request.form['age']),
'workplace': request.form['workplace'],
'favorite_food': request.form['favorite_food'],
'favorite_place': request.form['favorite_place'],
'latest_post': '',
'friends': []
}
return redirect(url_for('show_profile', username=username))
else:
return "Username already exists. Please choose another one."
return render_template('create_profile.html')
our create_profile.html to to get the new profile data
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Profile</title>
</head>
<body>
<h1>Create Your Profile</h1>
<form action="{{ url_for('create_profile') }}" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br>
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age" required><br>
<label for="workplace">Workplace:</label>
<input type="text" id="workplace" name="workplace" required><br>
<label for="favorite_food">Favorite Food:</label>
<input type="text" id="favorite_food" name="favorite_food" required><br>
<label for="favorite_place">Favorite Place:</label>
<input type="text" id="favorite_place" name="favorite_place" required><br>
<input type="submit" value="Create Profile">
</form>
</body>
</html>
Now our complete app.py code
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
users = {
'parrot': {
'name': 'Parrot',
'age': 5,
'workplace': 'Tropical Forest',
'favorite_food': 'Sunflower seeds',
'favorite_place': 'Jungle canopy',
'latest_post': 'Squawk!',
'friends': ['dog', 'cat']
},
'dog': {
'name': 'Dog',
'age': 3,
'workplace': 'Backyard',
'favorite_food': 'Bones',
'favorite_place': 'Dog park',
'latest_post': 'Woof!',
'friends': ['cat']
},
'cat': {
'name': 'Cat',
'age': 2,
'workplace': 'Living room',
'favorite_food': 'Fish',
'favorite_place': 'Sunny spot',
'latest_post': 'Meow!',
'friends': ['dog', 'parrot']
},
'rooster': {
'name': 'Rooster',
'age': 1,
'workplace': 'Farmyard',
'favorite_food': 'Grains',
'favorite_place': 'Chicken coop',
'latest_post': 'Cock-a-doodle-doo!',
'friends': []
}
}
@app.route('/')
def index():
return render_template('index.html', users=users)
@app.route('/<username>')
def show_profile(username):
if username in users:
user = users[username]
return render_template('profile.html', user=user)
else:
return "User not found", 404
@app.route('/create_profile', methods=['GET', 'POST'])
def create_profile():
if request.method == 'POST':
username = request.form['username']
if username not in users:
users[username] = {
'name': request.form['name'],
'age': int(request.form['age']),
'workplace': request.form['workplace'],
'favorite_food': request.form['favorite_food'],
'favorite_place': request.form['favorite_place'],
'latest_post': '',
'friends': []
}
return redirect(url_for('show_profile', username=username))
else:
return "Username already exists. Please choose another one."
return render_template('create_profile.html')
if __name__ == '__main__':
app.run(debug=True)
Get this project complete code from github and customize the code on your necessary. The code is for starting purpose for your project. You can add more features like profile pictures, sending friend request or more! As a learning project it can be a great beginning!