考虑到我有1个资源和2个网址(例如,新的和旧的)连接到该资源。因此,我想为其中一个网址设置HTTP重定向。

myapp/urls.py中,我有:

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

mycoolapp/urls.py中,我要指定:
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'
                                 ),
                       }
   ),
)

问题是如何将<param>传递给reverse_lazy kwargs(因此,在上面的示例中要放置什么代替<???>)?

最佳答案

我不会直接在urls.py中执行此操作,而是使用基于类的RedirectView计算要重定向到的 View :

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')

然后,在urls.py中,您可以执行以下操作:
urlpatterns = patterns('',
    url(r'^coolresource/(?P<param>\d+)/$',
        RedirectSomewhere.as_view()),
)

关于django - 如何在Django urls.py中将url参数传递给reverse_lazy,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9879259/

10-12 22:01