How to pass url parameter to reverse_lazy in Django urls.py

gakhov picture gakhov · Mar 26, 2012 · Viewed 35k times · Source

Consider that I have 1 resource and 2 urls (let's say new one and old one) connected to that resourse. So, i want to setup HTTP redirection for one of urls.

In myapp/urls.py I have:

urlpatterns = patterns('',
    url(r'^(?P<param>\d+)/resource$', 
                      'myapp.views.resource', 
                       name='resource-view'
    ),
)

In mycoolapp/urls.py I want to specify:

from django.views.generic.simple import redirect_to
from django.core.urlresolvers import reverse_lazy

urlpatterns = patterns('',
    url(r'^coolresource/(?P<param>\d+)/$', 
                       redirect_to, 
                       {
                          'url': reverse_lazy('resourse-view', 
                                         kwargs={'param': <???>}, 
                                         current_app='myapp'
                                 ),
                       }
   ),
)

The question is how to pass <param> to the reverse_lazy kwargs (so, what to put instead of <???> in the example above)?

Answer

slurms picture slurms · Jan 23, 2013

I wouldn't do this directly in the urls.py, I'd instead use the class-based RedirectView to calculate the view to redirect to:

from django.views.generic.base import RedirectView
from django.core.urlresolvers import reverse_lazy

class RedirectSomewhere(RedirectView):
    def get_redirect_url(self, param):
        return reverse_lazy('resource-view',
                            kwargs={'param': param},
                            current_app='myapp')

Then, in your urls.py you can do this:

urlpatterns = patterns('',
    url(r'^coolresource/(?P<param>\d+)/$', 
        RedirectSomewhere.as_view()),
)