Python Django Handling Custom Error Page


Every web site needs to handle errors like HTTP 404 “page not found” or 500 “internal server errors”. For Django based web server when these errors occur, the web server will show active server’s settings. I added basic steps about handling Custom Error Page. For production service it should be more critical then development platform disables DEBUG mode and also customize error pages.

By default, Python Django manages these error codes with handlerxxx under urls.py file.

URL dispatcher | Django documentation | Django
A clean, elegant URL scheme is an important detail in a high-quality Web application. Django lets you design URLs…docs.djangoproject.com

handler404 = ‘myapp.views.error_404’
handler500 = ‘myapp.views.error_500’
handler403 = ‘myapp.views.error_403’
handler400 = ‘myapp.views.error_400’

Step 1: Edit settings.py file

1.1 Change debug level

Filename:settings.py

DEBUG = False
ALLOWED_HOSTS =  ['localhost', '127.0.0.1']

1.2 Define template directory for HTML

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR, ],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

1.3 Add installed  application to configuration

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'jquery',
'certman'
]

Step 2: Add the handler method to urls.py

There are 4 already defined handler methods in django.urls functions. To change default configuration;

For my project “myappname” is “certman”.

Filename: urls.py

handler404 = 'myappname.views.error_404'
handler500 = 'myappname.views.error_500'
handler403 = 'myappname.views.error_403'
handler400 = 'myappname.views.error_400'

Step 3: Edit views.py file

You need to define an error function to the views.py. Add these lines to manage handlerxxx.

Filename: views.py

from django.shortcuts import render

def error_404(request, exception):
        data = {}
        return render(request,'certman/404.html', data)

def error_500(request,  exception):
        data = {}
        return render(request,'certman/500.html', data)
 

Step 4: Define HTML file (404.html, 500.html, etc)

Add customized HTML files under the templates directory.

Step 5: Restart python Django project

#python manage.py runserver

I'm a IT Infrastructure and Operations Architect with extensive experience and administration skills and works for Turk Telekom. I provide hardware and software support for the IT Infrastructure and Operations tasks.

205 Total Posts
Follow Me