[Django]-Urls.py redirect with URL reversal and parameters โ€” is there any easier way?

1๐Ÿ‘

You have some options here. You can use RedirectView, but I was unable to get it to reverse urls, since it looks like it runs before urlpatterns loads up. You can use it like so, tailor this to be used in your project:

from django.views.generic import RedirectView

Add this to your urlpatterns:

url(r'^(?P<location_id>\d+)/$', RedirectView.as_view(url='/statistics/dailyreport/%(location_id)s/')),

USE LAMBDA: This should work in most versions of django, I am using it in 1.6.5:

from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
urlpatterns = patterns('',
    ....
    url(r'^(?P<location_id>\d+)/$', lambda x, location_id: HttpResponseRedirect(reverse('dailyreport_location', args=[location_id])), name='location_stats_redirect'),
    ....
)
๐Ÿ‘คradtek

0๐Ÿ‘

Just a quick note that in your reg exp you can use [0-9] instead of [0123456789]

๐Ÿ‘คQuantumLicht

Leave a comment