What are built-in error views in Django?

Introduction

Built-in errors in a web application usually give users a 404 message, which means a page could not be found. There are other similar errors, such as 403, 400, and 500. We categorize all such errors as HTTP errors.

Types of HTTP errors

Some examples of HTTP errors are explained below:

  • 404 error: This is also known as a page not found error. It usually pops up if the page we try to access does not exist.

    • When this happens, Django raises django.views.defaults.page_not_found(), which in turn renders the default 404 error template.
    • We can customize it by adding a 404.html file in the template folder.
  • 403 error: This is also known as a forbidden page error. It usually pops up when the user is not authenticated or permitted to access a certain page or perform a certain action in the web application. For example, the user may not be logged in or granted super-user abilities to access, delete, or change certain files.

    • When this happens, Django raises django.views.defaults.permission_denied(), which in turn renders the default 403 error template.
    • We can customize it by adding a 403.html file in the template folder.
  • 400 error: This is also known as bad request view. It usually pops up either when a user tries to access and pull out confidential data in the website, or when a file’s size is too large, corrupting browser cache and cookies. This error usually helps prevent the event of being hacked by other users.

    • When this happens, Django raises django.views.defaults.bad_request(), which in turn renders the default 400 error template.
    • We can customize it by adding a 400.html file in the template folder.
  • 500 error: This is also known as an internal server error. It usually pops up when there is a runtime error in the view code, and during failures when collecting static files.

    • When this happens, Django raises django.views.defaults.server_error(), which in turn renders the default 500 error template.
    • We can customize it by adding a 500.html file in the template folder.

Example

Let’s get to the code.

Step 1

We use the following commands to create a virtual environment, and also install Django:

pip install pipenv 
pipenv shell
pipenv install django

Step 2

We create the project and its application:

django-admin startproject Educative ./
python manage.py startapp codebase

Step 3

We migrate everything in the Django application, and start the server:

python manage.py migrate
python manage.py runserver

Step 4

We go to settings.py and enter the following:

# Set debug to false
DEBUG = False
# To allow any host
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'codebase',
]

Step 5

We go to urls.py file and enter the following:

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('/home', include('codebase.urls'))
]
# Customizing the built error pages
handler404 = 'codebase.views.error_404'
handler500 = 'codebase.views.error_500'
handler403 = 'codebase.views.error_403'
handler400 = 'codebase.views.error_400'

Step 6:

In the codebase application folder, we go to views.py:

from django.shortcuts import render
def error_404(request, exception):
return render(request, 'app/404.html')
def error_500(request, *args, **argv):
return render(request, 'app/500.html', status=500)
def error_403(request, exception):
return render(request,'app/403.html')
def error_400(request, exception):
return render(request,'app/400.html')

Step 7

  • In the codebase app, we create a folder and name it templates.

  • Inside the templates folder, we create another folder and name it app.

  • Inside the app folder, we create the 404.html, 400.html, 403.html, 500.html files and customize them to our taste.

<!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>Document</title>
</head>
<body>
<P> PAGE NOT FOUND, 404</P>
</body>
</html>

Step 8

To test our app, we run the following command:

python manage.py runserver

We can type anything at the end of http://127.0.0.1:8000 to get a 404 error that isn’t listed as a route in the Django application.

Note: We must remember to set DEBUG = false in our settings.py file to get the customized page.

The following is a screenshot of a customized 404 page that pops up when we type a route that doesn’t exist. Once we execute all the commands above, click the “Run” button to see the results.

Note: We have set everything on our platform. You don’t need to type any commands here.

Bud1

ocblob
appIlocblob;(������appbwspblob�bplist00�			
	]ShowStatusBar[ShowPathbar[ShowToolbar[ShowTabView_ContainerShowSidebar\WindowBounds[ShowSidebar			_{{627, 206}, {770, 436}}	%1=I`myz{|}~��appvSrnlongbuilt_in_errorsIlocblob�(������built_in_errorsbwspblob�bplist00�			
	]ShowStatusBar[ShowPathbar[ShowToolbar[ShowTabView_ContainerShowSidebar\WindowBounds[ShowSidebar			_{{627, 206}, {770, 436}}	%1=I`myz{|}~��built_in_errorsvSrnlong	manage.pyIlocblob�(������PipfileIlocblob�(������Pipfile.lockIlocblob;�������	README.mdIlocblob�������� @� @� @� @E
DSDB `� @� @� @

Free Resources