custom 404 page flask

  1. Import Flask:
from flask import Flask, render_template
  1. Create an instance of the Flask class:
app = Flask(__name__)
  1. Define a custom 404 error handler function:
@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html'), 404
  1. Create a template for the custom 404 page (assuming you have a 'templates' folder in your project directory):
  2. Create a file named '404.html' in the 'templates' folder.
  3. Customize the HTML content for your 404 page.

Example '404.html':

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>404 Not Found</title>
</head>
<body>
    <h1>404 Not Found</h1>
    <p>Sorry, the page you are looking for does not exist.</p>
</body>
</html>
  1. Run the Flask application:
if __name__ == '__main__':
    app.run(debug=True)

Ensure that the 'templates' folder containing the '404.html' file is in the same directory as your Flask application. This implementation will render the custom 404 page when a 404 error occurs in your Flask application.