vg3y1a
Last Updated: February 25, 2016
·
3.904K
· tim_heap
4ea13c0ade9aa384ebaa29b433c39421

Django URL redirect shortcut

Redirect from urls.py to another named URL, without having to create a whole new view:

from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect

def lazy_redirect(name, args=None, kwargs=None,
    http_response=HttpResponseRedirect):
    """
    Make a redirect view directly from `urls.py`.
    Takes the same arguments as
    `django.core.urlresolvers.reverse`, with an
    additional argument `http_response`. Use
    `http_response` to change the HttpResponse class
    used in the redirect. It defaults to
    `HttpResponseRedirect`.
    """

    def redirect(_):
        destination = reverse(name,
            args=args,
            kwargs=kwargs)
        return http_response(destination)

    return redirect


urlpatterns = patterns('',
    url(r'^redirect-me/$', lazy_redirect(
        'page.view_page',
        kwargs={'name': 'landing-page.html'})
)
Say Thanks
Respond