Customize Built-in Error Views in Django –

Now, let’s see how to customize these error views. First of all you need to go into settings.py and set Debug=False.

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

Make folder inside the project and name it anything, here I am giving name ‘templates‘ to that folder.  Now go to settings.py and set templates directory.

TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')

Now, inside the templates directory you can create html files ‘404.html’, ‘500.html’, ‘403.html’, ‘400.html’, etc. After creating these pages show your HTML skills and customize pages by yourself. Add your app name into settings.py.

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

Add the handler method to urls.py

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

Now set logic to show these pages in views.py

from django.shortcuts import render

def error_404(request, exception):

        return render(request,'404.html')

def error_500(request,  exception):
        return render(request,'500.html', data)
        
def error_403(request, exception):

        return render(request,'403.html')

def error_400(request,  exception):
        return render(request,'400.html', data)    

Now, you are all set to run the server and see these error handling pages made by you.

To run server: python manage.py runserver

Built-in Error Views in Django

Whenever one tries to visit a link that doesn’t exist on a website, it gives a 404 Error, that this page is not found. Similarly, there are more error codes such as 500, 403, etc. Django has some default functions to for handle HTTP errors. Let’s explore them one-by-one.

Similar Reads

Built-in Error Views in Django –

404 view (page not found) –...

Customize Built-in Error Views in Django –

Now, let’s see how to customize these error views. First of all you need to go into settings.py and set Debug=False....