python – urls.py重定向与URL反转和参数 – 有更简单的方法吗?
给定两类实体,我选择了一些具有以下URL定义的交叉产品集:
url(r"^category1/(?P<category1>([0123456789]+,?)+)/category2(?P<category2>([0123456789]+,?)+)/$",view,{},name="cross") 所以基本上像/ category1 / 1,2,3,4 / category2 / 5,6,7,8 /这样的URL是有效的. 现在我在相同的数据上引入了几个视图,所以现在我有像/ category1 / 1,8 / view1 /和/ category1 / 1,3这样的URL,4 /类别2 / 5,8- /视图2 /.我想将“旧”网址重定向到view1.我没有找到比这更容易的东西: url(r"^category1/(?P<category1>([0123456789]+,redirect_to,{ 'url': lazy(lambda: reverse( 'cross_view1',kwargs={ 'category1': '222221','category2': '222222',} ).replace('222221','%(category1)s') .replace('222222','%(category2)s'),str)(),name="cross"} 这里的要点是我想在URL中重用我匹配的组,但是,我不能将它们作为kwargs给redirect_to,因为它们不会被插值,也不能在URL中放入逐字格式,因为它必须匹配我的正则表达式(以逗号分隔的数字ID).所以我介绍一些独特的ID(在这种情况下为222221和222222)并在之后替换它们. 显然,这种感觉,外观,气味和味道非常黑客.有没有更简洁的方法来做到这一点,除了引入一个额外的视图和完全跳过redirect_to? 解决方法
你有一些选择.你可以使用RedirectView,但我无法让它反转url,因为它看起来像在urlpatterns加载之前运行.您可以像这样使用它,定制它以在您的项目中使用:
from django.views.generic import RedirectView 将其添加到您的urlpatterns: url(r'^(?P<location_id>d+)/$',RedirectView.as_view(url='/statistics/dailyreport/%(location_id)s/')), 使用LAMBDA:这应该适用于django的大多数版本,我在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'),.... ) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |