Sometimes in a project, you need to perform a simple redirect, pointing one URL to another.  For example, in a current project, I want the / URL to redirect to /shop.  I don’t need any complicated routing; I just need to rewrite one URL to another. Should be easy enough, right?

Following the Django docs, the suggested solution is to create a custom view function that takes care of the redirection, like so:

from django.http import HttpResponseRedirect

def redirect_to_shop(request):
    return HttpResponseRedirect("/shop/")

Of course, you also need to reference this from your main URL conf, like so:

urlpatterns = patterns('',
    (r'^$', views.redirect_to_shop),
    ...
)

But this approach leaves me unsatisfied. I’m not particularly fond of writing special view functions just to handle specific cases — but more importantly, for maintenance reasons, I really dislike any solution that requires me to update my code in more than one place. Splitting this code up between views.py and urls.py might be following the idiom correctly, but it’s not necessary, from a technical perspective.

There actually is a simpler, more efficient solution that makes idiomatic sense as well. Since this simple redirect is all about changing one URL into another, it makes sense to keep this functionality completely within the urls.py file. And it can be done right within the URL patterns with a one-line lambda function:

from django.http import HttpResponseRedirect

urlpatterns = patterns('',
    (r'^$', lambda x: HttpResponseRedirect('/shop/')),
    ...
)

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.

That’s it!