Python django中URL的排序

Python django中URL的排序,python,django,Python,Django,我遇到了一个奇怪的问题,虽然我现在已经找到了一个解决方案,但我认为了解是什么原因导致了错误是有帮助的。我在Django项目中有一个应用程序,URL如下: urlpatterns = patterns('', url(r'^$', UserProfileListView.as_view(), name='userprofile_list'), url(r'^(?P<username>[\w.@+-_]+)/changepassword/$',

我遇到了一个奇怪的问题,虽然我现在已经找到了一个解决方案,但我认为了解是什么原因导致了错误是有帮助的。我在Django项目中有一个应用程序,URL如下:

  urlpatterns = patterns('',
    url(r'^$', UserProfileListView.as_view(),
        name='userprofile_list'),
    url(r'^(?P<username>[\w.@+-_]+)/changepassword/$',
        password_change, name='change_password'),
    url(r'^(?P<username>[\w.@+-_]+)/$',
        profile_detail,
        name='userprofile_detail'),
)
    urlpatterns = patterns('',
url(r'^$', UserProfileListView.as_view(),
    name='userprofile_list'),
url(r'^(?P<username>[\w.@+-_]+)/$',
    profile_detail,
    name='userprofile_detail'),
url(r'^(?P<username>[\w.@+-_]+)/changepassword/$',
    password_change, name='change_password'),

)
urlpatterns=patterns(“”,
url(r'^$',UserProfileListView.as_view(),
name='userprofile_list'),
url(r'^(?P[\w.@+-\]+)/changepassword/$,
密码\u更改,name='change\u password'),
url(r'^(?P[\w.@+-\]+)/$,
剖面图/详细信息,
name='userprofile_detail'),
)
当我指向浏览器更改密码时,一切正常。但是,我的URL顺序如下:

  urlpatterns = patterns('',
    url(r'^$', UserProfileListView.as_view(),
        name='userprofile_list'),
    url(r'^(?P<username>[\w.@+-_]+)/changepassword/$',
        password_change, name='change_password'),
    url(r'^(?P<username>[\w.@+-_]+)/$',
        profile_detail,
        name='userprofile_detail'),
)
    urlpatterns = patterns('',
url(r'^$', UserProfileListView.as_view(),
    name='userprofile_list'),
url(r'^(?P<username>[\w.@+-_]+)/$',
    profile_detail,
    name='userprofile_detail'),
url(r'^(?P<username>[\w.@+-_]+)/changepassword/$',
    password_change, name='change_password'),

)
urlpatterns=patterns(“”,
url(r'^$',UserProfileListView.as_view(),
name='userprofile_list'),
url(r'^(?P[\w.@+-\]+)/$,
剖面图/详细信息,
name='userprofile_detail'),
url(r'^(?P[\w.@+-\]+)/changepassword/$,
密码\u更改,name='change\u password'),
)
由于视图接收的是username=username/changepassword,而不是username=username,因此未找到404页错误


url被如此解读的原因是什么?为什么它在一开始就起作用?

丹·克拉松的评论就是答案。只需详细说明一下,您可以通过测试regexp轻松发现:

>>> import re
>>> re.match(r"^(?P<username>[\w.@+-_]+)/$", "foobar/changepassword/")
<_sre.SRE_Match object at 0x7f949c54be40>

因为第一个正则表达式同时捕获了这两个。这就是为什么订单很重要。