By continuing to navigate on this website, you accept the use of cookies to serve you more relevant services & content.
For more information and to change the setting of cookies on your computer, please read our Cookie Policy.

Handling Custom Error Pages(404, 500) In Django

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. Nginx or apace by default serve 404 and 500 pages when DEBUG=False, which are not user-friendly. 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.

    Posted On
  • 15 April 2014
  • By
  • Micropyramid

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Custom validations for serializer fields Django Rest Framework

we can write custom validations for serializer fields in Django Rest Framework. Validators are used to validate the data whether it is semantically valid or ...

Continue Reading...
Deploying Your Django app on Heroku

Heroku is a platform as a service (PaaS) that enables developers to build and run applications entirely in the cloud.
1. installation
2. Creating and ...

Continue Reading...
What's great about Django girls to inspire women into programming

Django girls is a non-profit organization, that helps women to learn Django programming language and to inspire them into programming. They are organizing workshops all ...

Continue Reading...
open source packages

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties