Django tip: Redirecting straight from urls.py

You don't need custom view to redirect URLs.

Published: Oct. 24, 2021
App Store

This might be obvious to you if you are used to working with Class-based Views, but for me this was new and pretty cool.

I wanted to redirect one URL to another view and before implementing lean function view with the redirect function, I decided to look if better solution exists.. And indeed it does. Meet RedirectView.

You can use it inline in your urls.py to greatly simplify things. It can redirect either based on another route name or to any arbitrary URL.

For example here is usage from my project:

urlpatterns = [
    path('', RedirectView.as_view(pattern_name='profile-detail', permanent=True)),
]

These are URL patterns prefixed with account and I wanted the unspecified URL to redirect to account/profile which this accomplishes. The permanent settings dictate whether 301 or 302 is returned as a status code.

Instead of pattern_name you can use url attribute and redirect to anywhere. Or you can pass None there to raise status code 410, which means that this URL is no longer available.

And last attribute query_string lets us specify whether possible query string in the URL should be kept (True) or removed (False, default value).

And that's it!

This can be useful also to redirect .well-known URLs, like the one for password change or to redirect your RSS feed if you decide to move it to another URL.

Bluesky logo

Follow on Bluesky to not miss new posts

Filip Němeček profile photo

WRITTEN BY

Filip Němeček Mastodon

iOS blogger and developer with interest in Python/Django.

iOS blogger and developer with interest in Python/Django.