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 basically works by creating a table in the database with two columns, old_path
and new_path
. Every time your
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
, instead of raising the 404 error, it will redirect the user
to the new_path
returning a 301 code (Moved Permanently).
Alright, so let’s see how it works in practice.
Installation
The Django Redirects App requires the sites
framework to be installed. You can install them by adding the apps to
your project’s INSTALLED_APPS
:
settings.py
Set a SITE_ID
so the sites framework works properly.
settings.py
Now, add the redirects middleware to the MIDDLEWARE
configuration:
settings.py
Make sure you run the migrate
command to create the required tables:
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.
You will see, it’s very straightforward. Just add the paths and it will do all the hard work for you.
We can test it by typing the old path in the browser and see if redirects correctly. Another way is examining the
response body in the terminal. You can easily do it by using curl
:
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
You can start a Python shell with your project models loaded by running the following command:
Here is how you can create a few redirect entries:
Using the Redirects App with Fixtures
Just create a JSON file following the template of the example below:
redirects-fixture.json
Then you can load it directly to your database by running the command below:
And that’s it!