Handling Custom Error Pages(404, 500) In Django

Reading Time : ~ .

404 Page not found and 500 Internal server errors generally occur on every website. When these errors occur, generally for Django application it will load a page showing the application settings. So to avoid settings open, we'll keep DEBUG=False in production mode. But keeping DEBUG=False by default the pages will be served by web servers like Nginx or apache which won't look good for an end user point of view. So in order to display better looking UI to the end user, we'll customize the Django's built-in 404 and 500 pages.

By default, these error pages are handled by handlerxxx views. For example 404 errors will be served by handler404 view, similarly, 500 Internal server error will be handled by handler500. So in order to display our custom pages instead of web server's pages, we will override the Django's handlerxxx views.

In your views.py

def handler404(request):
    return render(request, '404.html', status=404)

def handler500(request):
    return render(request, '500.html', status=500)

Now just specify these in your urls.py as below.

handler404 = myapp.views.handler404
handler500 = myapp.views.handler500

In settings.py

You need to add your hostname in ALLOWED_HOSTS like:

ALLOWED_HOSTS = ['testsite.com', 'localhost']

With the above steps, we'll get to see your own custom error pages served by Django's views with better UI.

    By Posted On
SENIOR DEVELOPER at MICROPYRAMID

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Using Sentry To Track Django live Events Jagadeesh V

Let us now learn how to track exceptions and events in SENTRY. We will setup browser and server end tracking for Django Project.

Continue Reading...
Django Raw Sql Queries Vamsi Popuri

When your model query API don't go well or you want more performance, you can use raw sql queries in django. The Django Object Relational ...

Continue Reading...
How to Create your own e-commerce shop using Django-Oscar. Shirisha Gaddi

Oscar is an open-source ecommerce framework for Django. Django Oscar provides a base platform to build an online shop. Oscar is built as a highly ...

Continue Reading...

Subscribe To our news letter

Subscribe to our news letter to receive latest blog posts into your inbox. Please fill your email address in the below form.
*We don't provide your email contact details to any third parties