Redirects in Django urls including parameters
A change of url schemata forced me to redirect some urls in my Django app. I wanted to use reverse, RedirectView and url parameters.
The View:
from django.views.generic import RedirectView from django.core.urlresolvers import reverse_lazy class RedirectViewCustom(RedirectView): """view to redirect including all named parameters to a specific lazy url name""" def get_redirect_url(self, **kwargs): params = self.kwargs name = self.kwargs.get('redirectname') if name: del params['redirectname'] return reverse_lazy(name, kwargs=params) else: raise ValueError, "redirectname not set in RedirectViewCustom call."
In urls.py:
url(r'^old-name/(?P<slug>[a-zA-Z]+)/(?P<param>[a-zA-Z0-9-\-]+)/$', RedirectViewCustom.as_view(), kwargs={'redirectname':'some-name'}),
Tested with Django 1.4.