Building a Simple Portfolio Website with Flask

Welcome, aspiring web developers! Have you ever wanted to showcase your skills, projects, and connect with others online? A personal portfolio website is an excellent way to do just that. It acts like your digital business card and resume, all rolled into one beautiful package.

In this guide, we’re going to embark on an exciting journey to build a simple portfolio website using Flask. If you’re new to web development or Python, don’t worry! We’ll explain everything in easy-to-understand language, step by step. By the end of this tutorial, you’ll have a foundational understanding of how web applications work with Flask and a basic website to call your own.

What is a Portfolio Website and Why Do You Need One?

Imagine you’re applying for a job or trying to land a freelance project. Instead of just listing your achievements on a piece of paper, what if you could show off your actual work, provide links to your projects, and express your personality? That’s precisely what a portfolio website does. It’s your personal online space where you can:

  • Showcase your work: Display your best projects, designs, code, or writing samples.
  • Tell your story: Share your journey, skills, and what makes you unique.
  • Be accessible: Anyone, anywhere, can find out about you and your work.
  • Build your brand: Establish your professional online identity.

Why Choose Flask for Your Portfolio?

There are many ways to build a website, but Flask stands out as a fantastic choice, especially for beginners.

What is Flask?

Flask is a “micro-framework” for building web applications using Python.
* Framework: Think of a framework as a starter kit or a blueprint that provides a structure and common tools to help you build software. Instead of building everything from scratch, a framework gives you a head start.
* Micro-framework: This means Flask is lightweight and provides just the essentials to get a web application up and running. It doesn’t force you into a specific way of doing things, giving you a lot of flexibility. If you need more features (like database tools or user management), you can add them yourself.

Advantages of Flask for Beginners:

  • Python-based: If you already know Python, Flask makes web development feel familiar and intuitive.
  • Simple to start: You can get a basic web app running with just a few lines of code.
  • Flexible: It doesn’t come with many pre-built components, giving you the freedom to choose what you want to use.
  • Great for learning: Its simplicity helps you understand the core concepts of web development without getting overwhelmed.

Setting Up Your Development Environment

Before we write any code, we need to set up our workspace.

1. Install Python

Make sure you have Python installed on your computer. You can download it from the official Python website (python.org). We recommend Python 3.7 or newer.

2. Create a Project Folder

Let’s create a dedicated folder for our project. You can name it my_portfolio.

3. Set Up a Virtual Environment

A virtual environment is a fantastic tool that creates an isolated space for your Python project.
* Why use it? It prevents conflicts between different projects. For example, if Project A needs an older version of Flask and Project B needs a newer one, a virtual environment ensures they both work without issues.
* How to create it: Open your terminal or command prompt, navigate into your my_portfolio folder, and run:
bash
python -m venv venv

This command creates a new folder named venv inside your project directory, which contains our isolated Python environment.

4. Activate the Virtual Environment

Before installing Flask, you need to “activate” your virtual environment.
* On macOS/Linux:
bash
source venv/bin/activate

* On Windows (Command Prompt):
cmd
venv\Scripts\activate

* On Windows (PowerShell):
powershell
.\venv\Scripts\Activate.ps1

You’ll notice (venv) appearing at the beginning of your terminal prompt, indicating that the virtual environment is active.

5. Install Flask

With your virtual environment active, install Flask using pip (Python’s package installer).

pip install Flask

Our First Flask Application: “Hello, Portfolio!”

Now that everything is set up, let’s create the simplest Flask application.

1. Create app.py

Inside your my_portfolio folder, create a new file named app.py. This will be the main file for our Flask application.

2. Add the Basic Code

Open app.py and paste the following code:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Hello, Portfolio! This is my first Flask website."

if __name__ == '__main__':
    app.run(debug=True) # debug=True allows for auto-reloading on changes

Let’s break down this code:

  • from flask import Flask: This line imports the Flask class from the flask library.
  • app = Flask(__name__): This creates an instance of the Flask application. __name__ is a special Python variable that tells Flask where to look for resources like templates and static files.
  • @app.route('/'): This is a “decorator.” It tells Flask that whenever someone visits the root URL (/) of our website, the home() function should be called.
  • def home():: This is a Python function that defines what happens when the home route is accessed.
  • return "Hello, Portfolio! ...": This simply sends a text message back to the user’s web browser.
  • if __name__ == '__main__':: This is a standard Python idiom. It means the code inside this block will only run when the script is executed directly (not when imported as a module).
  • app.run(debug=True): This command starts the Flask development server. debug=True is very helpful during development because it automatically reloads the server when you make changes to your code and provides helpful error messages. Remember to turn debug=False for production!

3. Run Your Application

Save app.py, go back to your terminal (with the virtual environment still active), and run:

python app.py

You should see output similar to this:

 * Serving Flask app 'app'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: ...

Open your web browser and go to http://127.0.0.1:5000. You should see “Hello, Portfolio! This is my first Flask website.” Congratulations! You’ve just built your first Flask app.

Introducing Templates: Making Your Website Look Good (HTML)

Right now, our website only shows plain text. Real websites use HTML to structure their content. Flask makes it easy to use HTML files called “templates” to keep your Python code separate from your web page design. Flask uses a templating engine called Jinja2.

1. Create a templates Folder

Inside your my_portfolio directory, create a new folder named templates. Flask automatically looks for HTML files in this folder.

2. Create index.html

Inside the templates folder, create a file named index.html and add the following basic HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Awesome Portfolio</title>
</head>
<body>
    <h1>Welcome to My Portfolio!</h1>
    <p>This is where I showcase my skills and projects.</p>
    <p>Check back soon for more exciting content.</p>
</body>
</html>

3. Update app.py to Use the Template

We need to tell Flask to render our index.html file instead of just returning text. We’ll use the render_template function.

Modify your app.py like this:

from flask import Flask, render_template # Import render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html') # Use render_template to serve our HTML file

if __name__ == '__main__':
    app.run(debug=True)

Save app.py. Since debug=True is enabled, your server should automatically reload. Refresh your browser at http://127.0.0.1:5000. You should now see the content from your index.html file, formatted by your browser!

Adding Static Files: Styling with CSS

Websites don’t just have HTML; they also have CSS for styling (colors, fonts, layout) and sometimes JavaScript for interactivity. These are called “static files.”

1. Create a static Folder

Just like templates, Flask looks for static files in a special folder. Create a new folder named static inside your my_portfolio directory.

2. Create css Subfolder and style.css

Inside the static folder, create another folder called css. Then, inside the css folder, create a file named style.css.

Add some basic CSS to style.css:

/* static/css/style.css */
body {
    font-family: Arial, sans-serif;
    margin: 20px;
    background-color: #f4f4f4;
    color: #333;
    line-height: 1.6;
}

h1 {
    color: #0056b3;
    text-align: center;
}

p {
    margin-bottom: 10px;
    text-align: center;
}

nav ul {
    list-style-type: none;
    padding: 0;
    text-align: center;
    background-color: #333;
    overflow: hidden;
}

nav ul li {
    display: inline;
    margin: 0 15px;
}

nav ul li a {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

nav ul li a:hover {
    background-color: #575757;
}

3. Link style.css in index.html

Now, we need to tell our index.html to use this stylesheet. Open index.html and add the following line inside the <head> section, usually after the <title> tag:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Awesome Portfolio</title>
    <!-- Link to our CSS file -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
    <!-- ... rest of your body content ... -->
  • {{ url_for('static', filename='css/style.css') }}: This is a Jinja2 template function provided by Flask. It dynamically generates the correct URL for our static file. This is better than hardcoding the path because Flask can handle where your static files are located, even if you move them later.

Save index.html. Refresh your browser, and you should now see your “Welcome to My Portfolio!” text styled with the new font, colors, and centered alignment!

Building More Pages: About and Contact

A portfolio usually has more than just a home page. Let’s add an “About” page and a “Contact” page.

1. Create New Templates

Inside your templates folder, create two new files: about.html and contact.html.

about.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>About Me - My Awesome Portfolio</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
    <nav>
        <ul>
            <li><a href="{{ url_for('home') }}">Home</a></li>
            <li><a href="{{ url_for('about') }}">About</a></li>
            <li><a href="{{ url_for('contact') }}">Contact</a></li>
        </ul>
    </nav>
    <h1>About Me</h1>
    <p>Hi, I'm [Your Name]! I'm passionate about [Your Interest/Field].</p>
    <p>I enjoy building things and learning new technologies.</p>
    <p>Feel free to explore my projects!</p>
</body>
</html>

contact.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact Me - My Awesome Portfolio</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
    <nav>
        <ul>
            <li><a href="{{ url_for('home') }}">Home</a></li>
            <li><a href="{{ url_for('about') }}">About</a></li>
            <li><a href="{{ url_for('contact') }}">Contact</a></li>
        </ul>
    </nav>
    <h1>Contact Me</h1>
    <p>Have a project in mind or just want to say hello?</p>
    <p>You can reach me at: <a href="mailto:your.email@example.com">your.email@example.com</a></p>
    <p>Find me on LinkedIn: <a href="https://linkedin.com/in/yourprofile" target="_blank">Your LinkedIn</a></p>
</body>
</html>

Notice we’ve added a basic navigation bar (<nav>) to these pages, using {{ url_for('home') }}, {{ url_for('about') }}, and {{ url_for('contact') }} to link to our Flask routes.

2. Update app.py with New Routes

Now we need to create the corresponding routes in our app.py file.

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/about') # New route for the about page
def about():
    return render_template('about.html')

@app.route('/contact') # New route for the contact page
def contact():
    return render_template('contact.html')

if __name__ == '__main__':
    app.run(debug=True)

3. Add Navigation to index.html

To make it easy to navigate our site, let’s add the same navigation bar to our index.html as well.

Modify index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Awesome Portfolio</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
    <nav>
        <ul>
            <li><a href="{{ url_for('home') }}">Home</a></li>
            <li><a href="{{ url_for('about') }}">About</a></li>
            <li><a href="{{ url_for('contact') }}">Contact</a></li>
        </ul>
    </nav>
    <h1>Welcome to My Portfolio!</h1>
    <p>This is where I showcase my skills and projects.</p>
    <p>Check back soon for more exciting content.</p>
</body>
</html>

Save all your files. Your server should reload automatically. Now, refresh your browser at http://127.0.0.1:5000 and use the navigation links to explore your new pages!

Your Project Structure So Far

Here’s how your my_portfolio project folder should look:

my_portfolio/
├── venv/                 # Your virtual environment (ignore this folder)
├── app.py                # Main Flask application file
├── templates/
│   ├── index.html        # Home page HTML
│   ├── about.html        # About page HTML
│   └── contact.html      # Contact page HTML
└── static/
    └── css/
        └── style.css     # Our main stylesheet
    └── img/              # (Optional) For images like a profile picture

Next Steps and Taking Your Portfolio Further

Congratulations! You’ve successfully built a simple, multi-page portfolio website with Flask. This is just the beginning. Here are some ideas to expand your project:

  • Add more content: Fill your “About” page with your actual bio, skills, and experience. Create a “Projects” page to showcase your work with descriptions and links.
  • Images: Add a profile picture or project screenshots to your static/img folder and display them in your HTML using the <img> tag. Remember to use {{ url_for('static', filename='img/your-image.jpg') }} for the src attribute.
  • Forms: Implement a contact form using Flask-WTF to allow visitors to send you messages directly.
  • Database: For more complex features like a blog or dynamic project listings, integrate a database like SQLite and use an ORM (Object-Relational Mapper) like SQLAlchemy.
  • Deployment: Once your website is ready, you’ll want to make it live for the world to see! Look into services like Heroku, Render, Vercel, or DigitalOcean to deploy your Flask application.

Conclusion

Building a portfolio website with Flask is an excellent way to learn web development fundamentals. You’ve learned how to set up a Flask application, create routes, use HTML templates, and incorporate CSS for styling. Flask’s simplicity and Python’s power make it an enjoyable framework for beginners and experienced developers alike. Keep experimenting, keep building, and soon you’ll have a fantastic online presence that truly represents you!

Comments

Leave a Reply