0
0
DjangoHow-ToBeginner · 3 min read

How to Use Redirect in Django: Simple Guide with Examples

In Django, use the redirect() function from django.shortcuts to send users to another URL or view. It accepts a URL, view name, or model instance and returns an HTTP redirect response.
📐

Syntax

The redirect() function is used to return an HTTP redirect response. It can take:

  • A URL string (absolute or relative)
  • A view name (with optional arguments)
  • A model instance (which must have a get_absolute_url() method)

This function simplifies sending users to another page after an action.

python
from django.shortcuts import redirect

# Redirect to a URL
return redirect('/some/url/')

# Redirect to a view by name
return redirect('view-name')

# Redirect to a view with arguments
return redirect('view-name', arg1, arg2)

# Redirect using a model instance
return redirect(some_model_instance)
💻

Example

This example shows a Django view that redirects users to the homepage after a form submission.

python
from django.shortcuts import redirect
from django.http import HttpResponse

def submit_form(request):
    if request.method == 'POST':
        # Imagine form processing here
        return redirect('home')  # Redirect to the view named 'home'
    return HttpResponse('Please submit the form.')

def home(request):
    return HttpResponse('Welcome to the homepage!')
Output
When a POST request is sent to submit_form, the user is redirected to the home view, which shows 'Welcome to the homepage!'. For other methods, it shows 'Please submit the form.'
⚠️

Common Pitfalls

  • Forgetting to import redirect from django.shortcuts.
  • Passing a view function instead of its name as a string.
  • Not providing required arguments when redirecting by view name.
  • Using redirect() with a model instance that lacks get_absolute_url().

Always check that the target URL or view name is correct to avoid errors.

python
from django.shortcuts import redirect

# Wrong: passing view function instead of name
# return redirect(home)  # This may cause issues

# Right: pass view name as string
return redirect('home')
📊

Quick Reference

UsageDescription
redirect('/url/')Redirect to a specific URL string
redirect('view-name')Redirect to a named view without arguments
redirect('view-name', arg1)Redirect to a named view with positional arguments
redirect(model_instance)Redirect using model's get_absolute_url()

Key Takeaways

Use django.shortcuts.redirect to send users to another page easily.
redirect() accepts URLs, view names, or model instances with get_absolute_url().
Always import redirect and pass view names as strings, not functions.
Provide required arguments when redirecting to views that expect them.
Check your target URLs or view names to avoid runtime errors.