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)?
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()), )
Redirect View is great if you are using a hard coded url, it replaced redirect_to which is now deprecated. I don't think you can use it when redirecting and reversing from urls.py. Here is my solution, x is the response object in this case:
from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect urlpatterns = patterns('', .... url(r'^coolresource/(?P<param>\d+)/$', lambda x, param: HttpResponseRedirect( reverse('myapp.views.resource', args=[param]) ), name='resource-view-redirect'), .... )
You can still use the name of the url pattern instead of a hard coded url with this solution. The location_id parameter from the url is passed down to the lambda function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With