Django HTTP Redirects, Shortcuts & Custom Error Handlers

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.

The Essential Django Shortcuts

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)

Configuring Custom 404, 403 & 500 Error Handlers

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 %}

Testing Custom Error Pages Locally

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.

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What does get_object_or_404() do under the hood?

It attempts to call `get()` on the specified model or queryset. If the record does not exist (`Model.DoesNotExist`), it catches the exception and raises `django.http.Http404` instead of crashing with an uncaught 500 server error.

Q2. What is the difference between a 301 and a 302 HTTP redirect in Django?

A 302 redirect (`permanent=False`, the default in `redirect()`) indicates a temporary redirect. A 301 redirect (`permanent=True`) indicates that the URL has permanently moved to a new address, instructing search engines and browsers to cache the new location.

Q3. How do I create custom 404 and 500 error pages in Django?

Create templates named `404.html` and `500.html` inside your root template directory. When `DEBUG = False`, Django automatically renders these templates whenever an `Http404` or unhandled server exception occurs.

Q4. Why do custom 404/500 pages only show up when DEBUG is False?

When `DEBUG = True`, Django overrides standard error pages with its interactive traceback debugger to assist local development. Custom error templates are only displayed when `DEBUG = False`.

Explore Related Django Tutorials & Next Steps

Broaden your backend architecture, REST API design, and production engineering expertise:

URL Dispatcher & Reverse Resolution

Generate dynamic URLs using reverse() and the {% url %} template tag.

Function-Based Views (FBV)

Leverage get_object_or_404() to eliminate boilerplates.

Django Security Hardening

Protect against open redirect vulnerabilities with url_has_allowed_host_and_scheme.

130+ Django Interview Questions

Review HTTP status codes (200, 301, 302, 403, 404, 500) and handling.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!