How to Redirect URLs in Django

Posted: October 05, 2024 | Updated: October 06, 2024

Method 1. django-redirects

This built-in app in Django helps manage redirects through the admin interface.

Add django.contrib.sites, django.contrib.redirects to INSTALLED_APPS:

Open your settings.py file and make sure you have both django.contrib.sites and django.contrib.redirects included in the INSTALLED_APPS list:

   ...,
    'django.contrib.sites',
    'django.contrib.redirects',

Set Up Middleware

MIDDLEWARE = [
    ...,
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
    ...,
]

Set the SITE_ID:

You also need to define the SITE_ID in your settings.py. Typically, if you have just one site, you can set it to 1:

SITE_ID = 1

Run Migrations Make sure you’ve run the migrations for the redirects:

python manage.py migrate

Create Redirects in Admin

You need to create redirect entries in the admin panel. Make sure you have an admin user set up and access the redirects model:

  1. Navigate to http://localhost:8000/admin/
  2. Log in with your admin credentials.
  3. Look for "Redirects" in the admin interface and add a new redirect.

© 2024 Webapptiv. All rights reserved.