Graceful error handling and fluid navigation define professional web craftsmanship. When a user requests a deleted article or a system glitch occurs, your application must never leak Python stack traces or display generic browser crash screens. Django provides convenience shortcuts and customizable error handlers.
from django.shortcuts import render, redirect, get_object_or_404, get_list_or_404
from .models import BlogPost
def article_detail(request, slug):
# If article exists -> returns instance
# If missing -> automatically raises Http404 (renders 404.html)
article = get_object_or_404(BlogPost, slug=slug, is_published=True)
return render(request, 'blog/detail.html', {'article': article})
def legacy_url_redirect(request, old_slug):
# Permanent 301 SEO redirect to new endpoint
return redirect('blog:detail', slug=old_slug, permanent=True)
To override the default error presentations, declare custom handler variables in your root mywebsite/urls.py:
# mywebsite/urls.py
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
]
# Custom HTTP Error Handlers
handler400 = 'mywebsite.views.custom_bad_request_view'
handler403 = 'mywebsite.views.custom_permission_denied_view'
handler404 = 'mywebsite.views.custom_page_not_found_view'
handler500 = 'mywebsite.views.custom_server_error_view'
Create templates/404.html with helpful navigation options for lost visitors:
{% extends "base.html" %}
{% block title %}404 - Page Not Found | Veewom{% endblock %}
{% block content %}
<div class="text-center" style="padding: 60px 20px;">
<h1 style="font-size: 72px; color: #e65100; font-weight: 900;">404</h1>
<h2>Oops! That Page Seems to Have Wandered Off</h2>
<p class="cp">The tutorial or link you followed may have been updated or moved.</p>
<a href="{% url 'blog:post_list' %}" class="btn btn-primary">Browse All Tutorials</a>
</div>
{% endblock %}
To test your 404.html and 500.html templates locally without turning off debug mode across the entire project, temporarily toggle DEBUG = False and add ALLOWED_HOSTS = ['*'] in settings.py, then restart runserver.
Broaden your backend architecture, REST API design, and production engineering expertise:
Generate dynamic URLs using reverse() and the {% url %} template tag.
Leverage get_object_or_404() to eliminate boilerplates.
Protect against open redirect vulnerabilities with url_has_allowed_host_and_scheme.
Review HTTP status codes (200, 301, 302, 403, 404, 500) and handling.