Django tip: URL redirect shortcut
- December 12th, 2009
- Posted in Uncategorized
- Write comment
Bottom Line Up Front: Here’s a succinct, elegant way to do simple redirects in Django.
Sometimes in a web app, you need to perform a simple redirect, pointing one URL to another. For example, in a current project, I need the / URL to redirect to /shop. I don’t need any complicated routing; I just need to rewrite one URL to another. (And, as happens sometimes, I don’t want to fiddle with the web server conf to do it.)
The Django docs suggest creating a custom view function that takes care of the redirection. For example:
# urls.py
urlpatterns = patterns('',
(r'^$', views.redirect_to_shop),
...
)
# views.py
from django.http import HttpResponseRedirect
def redirect_to_shop(request):
return HttpResponseRedirect("/shop/")
...
Writing a custom view seems like a bit of overkill here. We don’t need to parse the request or do any complicated traffic routing; we just need to point url A to url B. Also, writing a custom view means maintaining code in both urls.py and views.py. I’d rather find a solution that can handle this simple request in a simpler, more efficient way.
This simple redirect can be implemented completely within the urls.py file, right within the URL patterns, using a one-line lambda function:
from django.http import HttpResponseRedirect
urlpatterns = patterns('',
(r'^$', lambda x: HttpResponseRedirect('/shop/')),
...
)
Voila. No need to write another function; no need to update your code in two places when you need to make a change. Everything is compact and in one place.
And yes, the “x” is necessary — Django will pass the request object to the lambda function, so if you don’t have something there to represent it, you’ll get a TypeError.
Cool tip!!
Thanks!
Thanks, this is handy!
You can also do it use:
from django.shortcuts import redirect
then you can use
redirect(‘url-name’)
And let the URL resolver deal with converting it to an absolute URL.