避免重复Django URL

时间:2015-07-01 15:24:00

标签: python django

我正在官方网站上制作Django教程,而我目前setting up URLs正在制作我们正在创建的示例投票应用程序。

截至目前,我的polls/urls.py看起来像这样:

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
    url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.votes, name='vote')
]

我无法帮助但是注意到(?P<question_id>[0-9]+)的重复,所以我想知道是否有一种更简单的方法可以避免这种情况,除了将它提取到像QUESTION_PATTERN = (?P<question_id>[0-9]+)这样的常量

1 个答案:

答案 0 :(得分:6)

您可以包含子模式列表,如下所示:

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^(?P<question_id>[0-9]+)/', include([
        url(r'^$', views.detail, name='detail'),
        url(r'^results/$', views.results, name='results'),
        url(r'^vote/$', views.votes, name='vote'),
    ]),
]