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'))
Written by Tomasz Walotek
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#