Django - Customized error 404 view for your applications

May 6, 2017 Djnago 中文版

In the first post, I already showed you how to configure logging settings. Let’s continue to explore other features provided by Django. In this article, I’m going to show you how to customize error 404 view for your applications.



Prerequisite

If you have not created a proper environment for the following steps, you can use below commands:

# Install Django
python -m pip install Django

# Check Django's version
python -m django --version

# Create a new Django project
django-admin startproject <project-name>

The structure of your project should look like this:

project-name/
├── project-name
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── wsgi.py


Create views for errors

Django already provides us a default mechanism and pages for handling error 404 or 50X. So, we don’t need to build things from scratch. First, create customized views in view.py like this:

# View for error 404
class Error404View(View):
    def get(self, request):
        # Do something if you want
        return render(request, 'path/to/error404.html')

# View for error 500
class Error500View(View):
    def get(self, request):
        # Do something if you want
        return render(request, 'path/to/error500.html')

In the example, I created two class-based views and specified HTML files for rendering.

Set URL configuration

At this point, Django doesn’t know when to use views that you just created. You need to let it know which views you want to use for error 404 or 50X, so put below settings in urls.py:

from django.conf.urls import handler404, handler500

# Import customized views
from your-app.views import Error404View, Error500View

urlpatterns = [
    ...
]

handler404 = Error404View.as_view()
handler500 = Error500View.as_view()

If you have multiple apps, you need to add those settings into your main url.py.

Test

To see the customized error pages, you have to disable debug mode. So, open your configuration settings.py, and disable it:

DEBUG = False

Now, the system will automatically display your customized pages when errors occur.


You might also like:




If you have any suggestions, questions or even find some typos, feel free to contact me. Thank you! :)

zeckli.devforgalaxy@gmail.com   © 2015-2019 zeckli, thanks to Jekyll and GitHub.