Last Updated: February 25, 2016
·
1.8K
· uolot

Redirect to named url in Django

Django doesn't allow you to use named url in your urlpatterns, following code will raise an exception:

(r'^blog/category/pictures/$',
  RedirectView().as_view(url='gallery-index'))

Also, calling reverse or even reverse_lazy in urls.py causes errors.
Here's a workaround:

from django.views.generic import RedirectView
from django.core.urlresolvers import reverse

class NamedUrlRedirectView(RedirectView):
    def __init__(self, url, *args, **kwargs):
        self.url = reverse(url)
        super(NamedUrlRedirectView, self) \
            .__init__(*args, **kwargs)

Then, in your url.py you can do this (after importing NamedUrlRedirectView):

(r'^blog/category/pictures/$',
    NamedUrlRedirectView().as_view(
        url='gallery-index'))