django url失败并带有可选参数

时间:2013-08-05 16:38:30

标签: python django url

以下是我的django路由配置:

# main module
urlpatterns = patterns('',
    url(r'^api/', include('api.urls')),
)

# api module
urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^users/(?P<id>\d+)/?$', views.users, name='users')
)

我可以使用http://localhost:8000/api/users/1/访问特定用户(使用ID)但我无法访问用户列表:http://localhost:8000/api/users/

Using the URLconf defined in duck_rip.urls, Django tried these URL patterns, in this order:
^api/ ^$ [name='index']
^api/ ^users/(?P<id>\d+) [name='users']
The current URL, api/users/, didn't match any of these.

在此之前,我的模块网址是这样的:

url(r'^users/$', views.users, name='users')

我可以访问http://localhost:8000/api/users/。有人可以解释一下我的错误是什么吗?

1 个答案:

答案 0 :(得分:4)

只需将id设为可选:

url(r'^users/(?:(?P<id>\d+)/)?$', views.users, name='users')

并且在视野中:

def users(request, id=None)