Learn how to use the Django custom 500 error template page. In this tutorial, you will learn how to create a custom page for internal server errors. And learn how to handle errors in Django with built-in views. Handler 500 is the built-in view. This will allow us to handle the 500 internal server errors using the custom template created by us.
pip install django
This command will install the latest Django package into your local machine.
Firstly Create a Django Project :
python -admin django startproject project
This command will create new project.
Navigate to Project folder :
cd project #projectname
This will change the current directory of the terminal to the project directory
Secondly Creating app with Demo app :
py manage.py startapp demo
Create a demo app for the Django project we have created.
Thirdly Create Urls.py in Demo app
from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home") ]
Here, We are creating the routing paths for the home view this will render out the Html page we have created for the model form. However the ” will represent the localhost path it will render the Html template as the homepage for the project on the localhost address. i.e. 127.0.0.1:8000. Get reference from Documentation
Creating views in demo app :
from django.shortcuts import render # Create your views here. def home(request): return render(request, 'home.html') def error_500(request): return render(request, '500.html') def check(): pass
Here we are creating the 3 views home and error_500. The home view will return the home.html page. And the error_500 view will return our custom 500 page which is a 500.html page. And finally check view is a dummy view which returns nothing. Hence it should raise an internal server error. This check view is only for checking 500 page status and optional.
Adding view handler to the main URLs :
from django.conf.urls import handler404, handler500 from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('demo.urls')) ] handler500 = 'demo.views.error_500'
Here the built-in handler will be overridden with the view in the demo app which is error_500. Nothing but the default template of the 500 internal server error given by Django will be modified by the 500.html in our project.
Change the Settings.py
# SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*']
Here we are changing the Settings.py file of the project we have created because. We have to change the DEBUG as False nothing but we are turning off the Django security to check the server. And again we need to modify the allowed host with ‘*’ because it allows every host user to access the content and render the handlers properly on localhost.
500 HTML template :
<html> <body> <h1>Internal server Error 500</h1> </body> </html>
Hence this is how we can use the Django custom 500 error template page.