How to create a Custom 404 page on Flask

flask custom 404 page 404 error page

A 404 page or error page is a web page that is displayed when a user attempts to access a non-existent page on a website. It provides the users with a more user-friendly experience when they land on a non-existent page. In this tutorial, we will be building a flask app with a custom 404 page. To learn more about flask, check their official documentation here.

To begin we need to first install flask . To install flask run the following command.

pip3 install flask

Next, we will need to create a folder for our app. Let’s call it flask-404. Inside the folder create a file called app.py. Create a folder called templates and add the following files index.html and 404.html

Now open the app.py and import the following.

from flask import Flask, render_template

Now let’s initialize the app by adding the following.

app = Flask(__name__)

Now let’s create a route to handle the main page.

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

The above code creates a home route and then we need to create a template for it. Add the following to the index.html page.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>My Website</title>
  </head>
  <body>
    <main  style="text-align : center;">
        <h1>Welcome to My Simple Flask Website</h1>
    </main>
  </body>
</html>

The above code will display the normal page in the home route.

Next, we need to create the page not found route which will be used to render the 404 page.

Inside the app.py add the following.

@app.errorhandler(404)
def page_not_found(e):
    return render_template("404.html"),404

Now let’s create the page not found template in the 404.html page.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>My Website</title>
  </head>
  <body>
    <main  style="text-align : center;">
        <h1>Welcome to My Simple Flask Website</h1>
    </main>
  </body>
</html>

Now let’s add the following to the app.py as we wind up.

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

Now our app is complete. To start the server run the command below.

python3 app.py

You can also use the command below.

flask run

Now open your browser and access the following address as shown below.

http://127.0.0.1:5000

You should now see the following.

If you try accessing a page that does not exist, you should automatically meet the 404 error page as shown below.

There you have it. Thanks for reading.

Leave a Comment

Your email address will not be published. Required fields are marked *