Creating a Custom 404 Page
Introduction: The Importance of a 404 Page
Welcome back! So far, you have learned how to create a reusable layout template and style your Cooking Helper frontend. Now, let’s talk about what happens when a user tries to visit a page that doesn’t exist on your site.
A “404 error” is what users see when they try to visit a page that isn’t found. By default, Flask (and most web servers) shows a plain, unfriendly error message. This can be confusing or frustrating for users. A custom 404 page helps your site look more professional and guides users back to where they want to go.
In this lesson, you’ll learn how to create a custom 404 page for your Cooking Helper site. This will make your site more user-friendly and show that you care about the user experience.
Recall: Flask Templates and Routing
Before we start, let’s quickly remind ourselves how Flask uses HTML templates and handles routes.
- Templates: In Flask, HTML files are stored in a
templatesfolder. You can use template inheritance to keep your pages consistent. - Routing: Flask uses routes to decide what content to show for each URL. If a user visits a URL that doesn’t match any route, Flask returns a 404 error.
You’ve already used templates and routes in previous lessons. Now, you’ll use these same ideas to handle errors in a friendly way.
Building the 404 Page Template
Let’s start by creating the HTML file for your custom 404 page.
Inside your templates folder, create a new file called 404.html. This file will be shown whenever a user visits a page that doesn’t exist.
We want our 404 page to look like the rest of the site. To do this, we’ll use template inheritance. This means our 404 page will extend the main layout template you built earlier.
Here’s how you start:
Let’s break this down:
{% extends "layout.html" %}tells Flask to use your main layout as the base for this page.{% block title %}sets the page title in the browser tab.{% block content %}is where the main message goes. Here, we show a big “404 - Page Not Found” message, a short explanation, and a link to go back to the home page.
This makes sure your 404 page matches the rest of your site and helps users find their way back.
