How to add a default 404 error page in Django?
404 is one of the most common errors for web applications to throw. But it is important to make sure that the end-user is not left hanging after a 404 error occurs, i.e. having no CTA (call to action) button available to the end-user. In the below example the end-user would have a very bad user experience and most likely would close the webpage.
To avoid such bad user experiences one can show a custom 404 page with a couple of CTA which can help the user to navigate to a page that has some information rather than closing the website.
In Django, it is very easy to write a custom 404-page logic, which would be shown by default to all the 404 errors.
- Go to the main
- Add the following snippet
# yourproject/url.py handler404 = "yourproject.exception.handler404"
- Now you need to create a new file
exception.pythat will have the
handle404logic to show a custom 404 page. You can create the above file in any other directory structure also, but you need to update the path in the handler404.
# yourproject/exception.py from django.shortcuts import render def handler404(request, *args, **argv): response = render(request, 'common/404.html') response.status_code = 404 return response
- In the above function, we are rendering a custom page template
common/404.htmland passing 404 status_code.
That's it. Now you have a custom default 404 page for all the requests which would previously throw a bad 404 error.