How to handle 404 and 500 errors in Django
In a web application, handling errors gracefully is crucial for providing a good user experience. By default, Django provides basic error pages, but you often want to customize them to match your website's design. In this post, we'll walk through how to add custom handlers for 404 (Not Found) and 500 (Internal Server Error) errors in Django.
First, we need to define the view functions that will render our custom error templates. These views should be simple and return the appropriate HTTP status code.
# frontend/views.py
from django.shortcuts import render
def handler404(request, exception):
return render(request, "frontend/404.html", status=404)
def handler500(request):
return render(request, "frontend/500.html", status=500)
Next, you need to tell Django which views to use as handlers. This is done by setting the handler404 and handler500 variables in your URL configuration file (usually your root urls.py or an app-specific one if it's included in the root).
# core/urls.py
from django.urls import path
from . import views
urlpatterns = [
# ... your paths ...
]
handler404 = "frontend.views.handler404"
handler500 = "frontend.views.handler500"
Finally, create the HTML templates that will be displayed to the users. For example, templates/frontend/404.html and templates/frontend/500.html. These templates can extend your base layout and provide helpful information or links back to the homepage.
Official Documentation
For more detailed information on customizing error views, check out the official Django documentation:
Django Customizing Error ViewsConclusion
Customizing error pages is a small but important detail that makes your application look more professional and keeps users engaged even when something goes wrong. Happy coding!