HOME > python

Creating custom error pages in Python Flask, 404

Last Modified : 2023-03-06 / Created : 2023-03-06
View Count

In creating an app using Python Flask, we will learn how to create a custom 404 error page that will be displayed when a page does not exist and a 404 error occurs.

# Python flask 404 custom error page
'404 means that the page does not exist. Web servers usually display an error message by default when a page is not found. However, if you want to display a custom 404 page for your website, many sites use them. Let's explore how to create a custom 404 page for an app using Flask.'

! Show a specific page when a 404 error occurs.
Flask has a very simple routing setup. If a 404 error occurs, it is possible to create a specific page or display a desired message. Usually, a custom error page is created to display it. Please see the code below.
from flask import render_template

def not_found_error(error):
  return render_template('page404.html')

Now a brief code has been completed that redirects visitors to a customized 404 page when they access a non-existent page on the website. If a 404 error occurs, not_found_error() is called and it will go to the newly created page404.html through render_template().
So far, we have looked at how to redirect to a 404 page in Flask.

! Other ways to display custom error pages.
Even if it is not a 404 error, it is also possible to display different custom errors for other errors such as 401, 403, etc. You just need to change the value of @application.errorhandler(404) above. It's like this.
def error_401(error):
  return render_template('page401.html')

def error_401(error):
  return render_template('page403.html')

Please note that other error handling methods are also possible.

We have learned how to create custom error pages in Python up to this point.


Post thumbnail [Python] Creating random numbers, using random


Check for the existence of a Python file, isfile Post thumbnail