Django Page Redirection: Complete Guide with Examples
Last updated 5 months, 3 weeks ago | 441 views 75 5
Redirecting users from one page to another is a common task in any web application. In Django, redirection can be handled easily and elegantly using built-in tools like HttpResponseRedirect, redirect(), and even URL configurations.
Whether you're redirecting users after login, form submission, or accessing a deprecated route, Django provides several ways to do it.
What is Page Redirection?
Redirection is when a user is automatically taken to a different URL. This is typically done using a 3xx HTTP status code — most commonly 302 (temporary) or 301 (permanent).
Methods of Redirecting in Django
✅ 1. Using HttpResponseRedirect
This is a subclass of HttpResponse that performs a redirect.
from django.http import HttpResponseRedirect
def my_view(request):
return HttpResponseRedirect('/new-url/')
Use Case: When you want precise control over the URL you're redirecting to.
✅ 2. Using redirect() Shortcut (Recommended)
A more convenient and readable way to redirect. It supports URLs, view names, and even model instances.
from django.shortcuts import redirect
# Redirect to a URL
def my_view(request):
return redirect('/new-url/')
# Redirect using view name (recommended)
def my_view(request):
return redirect('home')
# Redirect with parameters
def my_view(request):
return redirect('article_detail', slug='django-page-redirection')
Use Case: Clean, readable redirection in views.
✅ 3. Redirection in urls.py using RedirectView
You can redirect directly from urls.py using Django’s class-based view RedirectView.
from django.views.generic.base import RedirectView
from django.urls import path
urlpatterns = [
path('old-url/', RedirectView.as_view(url='/new-url/', permanent=True)),
]
✅ permanent=True sends a 301 Moved Permanently
✅ permanent=False (default) sends a 302 Found
Example: Redirect After Form Submission
from django.shortcuts import render, redirect
from .forms import ContactForm
def contact_view(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
form.save()
return redirect('thank_you') # Redirect to success page
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
Example: Redirect to Home Page
from django.shortcuts import redirect
def go_home(request):
return redirect('home') # 'home' is the name of a URL pattern
# urls.py
path('', HomeView.as_view(), name='home'),
path('go-home/', views.go_home),
Visiting /go-home/ takes the user to /.
Redirect with Parameters
def redirect_article(request):
return redirect('article_detail', slug='python-basics')
This assumes you have:
path('article/<slug:slug>/', views.article_detail, name='article_detail'),
Permanent vs Temporary Redirects
| Type | Code | Use Case |
|---|---|---|
| Temporary | 302 | Most common; resource may change |
| Permanent | 301 | URL will never return to old location |
In Django:
RedirectView.as_view(url='/new-url/', permanent=True) # 301
redirect('/new-url/') # 302 (default)
Full Example: Redirect After Login
from django.contrib.auth import authenticate, login
from django.shortcuts import render, redirect
def login_view(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('dashboard') # Redirect to user dashboard
return render(request, 'login.html')
Common Pitfalls
| Issue | Cause | Fix |
|---|---|---|
| Redirects to wrong URL | Missing or incorrect URL name | Double-check urls.py pattern names |
| Infinite redirects | Redirect loop caused by logic error | Add conditions to prevent repeating |
| Redirects to login page | @login_required decorator on view |
Make sure the user is authenticated |
NoReverseMatch |
Wrong view name or missing argument | Use correct view name and required kwargs |
Best Practices
-
✅ Use
redirect('view-name')for maintainability -
✅ Use
get_absolute_url()in models withredirect(obj) -
✅ Prefer named URL patterns (
name='...) over hard-coded URLs -
✅ Avoid hardcoded slugs/IDs in production
-
✅ Use
RedirectViewinurls.pyfor static redirects
Summary
| Method | Description | Example |
|---|---|---|
HttpResponseRedirect |
Manual redirect to URL | HttpResponseRedirect('/home/') |
redirect() |
Shortcut for flexible redirects | redirect('home') |
RedirectView |
Redirection in urls.py |
RedirectView.as_view(url='/new/', permanent=True) |
Want to Add Redirects After Login or Logout?
Django offers built-in settings:
LOGIN_REDIRECT_URL = '/dashboard/'
LOGOUT_REDIRECT_URL = '/'
These control where users are sent after login/logout using Django's LoginView and LogoutView.