Designing custom 404 and 500 error pages in Django

404 error page in Django

It happens very frequently that a visitor on your website typed a wrong URL or the page user is looking for no longer exists. What do you do to handle such cases.

You have three options.

  • Redirect the visitor to home page, silently.
  • Show a boring 404 page and then ask them to click on a link.
  • Create your own funny/awesome/informative custom 404 error page.

In this article we will discuss the third option.

How to create your own custom 404 error page in Django:

404 error page in Django

A custom 404 error page can serve multiple other purposes apart from just telling the user that the link you visited is not correct. You can ask user to subscribe or sign-up. Or you may show some funny stuff.

default 404 page in django

Default 404 error page in django is quite boring. Also creating a custom 404 page in django is very simple.  So lets see how to create custom 404 error page in django.

  • In urls.py  file of your project, import handler404  and handler505 .
  • In urls.py  file import views from your app.
  • After urlpatterns assign the views to handler404 and handler505.
  • In settings.py  file, set DEBUG=False  and ALLOWED_HOST=["*"] . Custom 404 and 500 pages works only when Debug is set to false and there is appropriate entry in allowed_hosts.
  • Create a new view function in your views file. Return the rendered 404 html file from this view. Make sure name of view function created in this file matches the name used in urls file above.
  • Now create an HTML template in your app’s template directory. Place whatever content you want to put there. You can create a subscribe form or sign up form.
  • Restart your http server if working on local or reload your app if project is hosted on pythonanywhere.com.
  • Now type an incorrect url and you will be shown your custom 404 page. In case of any internal server error like syntax error in some template, custom 500 page will be shown.

 

Comment in case of any query.

(Visited 3,300 times, 1 visits today)

You must read this :

Leave a Reply

Your email address will not be published. Required fields are marked *