Django Redirects App

Django comes with a few optional apps that can easily be installed. One of those apps is the Redirects App, which is particularly useful in the cases where you want to update some existing URLs without compromising your Website SEO or in any case avoid 404 errors.

It lets you store redirects in a database and handles the redirecting for you. It uses the HTTP response status code 301 Moved Permanently by default.

It basically works by creating a table in the database with two columns, old_path and new_path. Every time when website raises a 404 error, the Redirects App will intercept the response and check this particular table for a match. If the requested URL is found in the column old_path with respected site_id, instead of raising the 404 error, it will redirect the user to the new_path returning a 301 code (Moved Permanently).


Installation

  • The Django Redirects App requires the sites framework to be installed.
  • Add django.contrib.sites to the INSTALLED_APPS setting.
  • Add django.contrib.redirects to the INSTALLED_APPS setting.
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Sites and Redirect app
    'django.contrib.sites',
    'django.contrib.redirects',
]

Set a SITE_ID in the settings.py file so the sites framework works properly.

SITE_ID = 1
  • Add django.contrib.redirects.middleware.RedirectFallbackMiddleware to MIDDLEWARE configuration inside the setting.py.
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

    # Redirect Middleware
    'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
]

Make sure you run the migrate command to create the required tables:

$ python manage.py migrate  

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, redirects, sessions, sites
Running migrations:
  Applying redirects.0001_initial... OK
  Applying redirects.0002_alter_redirect_new_path_help_text... OK

Usage

  • The easiest way to use is through Django Admin.
  • If you are not currently using the Django Admin app, and it’s a one time thing (for example you are migrating a site from other platform), you can use just the Python API via command line or creating a fixture.
  • If you are not using Django Admin and still wants to add it as a functionality for the site administrator, then you will have to create your own views for it.

Using the Redirects App with Django Admin

It will be automatically added to the Django Admin interface.

redirect.png

You will see, it’s very straightforward. Just add the paths and it will do all the hard work for you.

redirect_url.png

Now, we can test it by typing the old path in the browser and see if redirects correctly or not. Another way is examining the response body in the terminal. You can easily do it by using curl:

curl --head 127.0.0.1:8000/contact-us/

HTTP/1.1 301 Moved Permanently
Date: Mon, 03 Oct 2022 10:41:34 GMT
Server: WSGIServer/0.2 CPython/3.8.12
Content-Type: text/html; charset=utf-8
Location: /about/
X-Frame-Options: DENY
Content-Length: 0
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin

Using the Redirects App with the Python API

You can manually create the redirect records interacting directly with the Redirect model. It lives in django/contrib/redirects/models.py

Open the python shell:

python manage.py shell

Here is how you can create a few redirect entries:

>>> from django.contrib.redirects.models import Redirect
>>> from django.contrib.sites.models import Site
>>> from django.conf import settings

>>> site = Site.objects.get(pk=settings.SITE_ID)

>>> # Add a new redirect.
>>> Redirect.objects.create(site=site, old_path='/contact-us/', new_path='/about/')

>>> # Delete a redirect.
>>> Redirect.objects.filter(site_id=1, old_path='/contact-us/').delete()

Using the Redirects App with Fixtures

Just create a JSON file following the template of the example below:

[
   {
      "model":"redirects.redirect",
      "fields":{
         "site":1,
         "old_path":"/contact-us/",
         "new_path":"/about/"
      }
   }
]

Then load it directly to the database by running the command below:

python manage.py loaddata redirects-fixtures.json
Installed 1 object(s) from 1 fixture(s)

If you want to find out more about the Redirects app, refer to the Django’s Official documentation about it.

Explore More Django Posts

Efficient Django Project Settings with Split Settings Library

Learn how to efficiently manage your Django project settings with the Split Settings library. Use environment variables, keep sensitive information i…

Read More
Integrating Flake8 with Django: Best Practices

Learn how to integrate Flake8 with Django projects and enforce code quality. Follow our step-by-step guide and optimize your Django workflow with Fla…

Read More
Django Authentication and Authorization with JWT

Learn how to implement JSON Web Token (JWT) based authentication and authorization in Django web applications with step-by-step guide and code exampl…

Read More
Best Practices for Django Development: Tips and Tricks

Learn the best practices for Django development, including project structure, code organization, testing, and deployment. Build high-quality web apps.

Read More
Django Middleware: Tips, Tricks and Examples

Learn how to use Django Middleware to improve your app's performance and security. Includes examples and best practices.

Read More
Django Production Deployment: Best Practices & Checklist

Learn the best practices and checklist for deploying a Django application to production. Includes tips on web servers, databases, caching, security, …

Read More