简体   繁体   中英

django url fails with optional parameters

Below is my django routing configuration:

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

I can access specific users (using ids) with http://localhost:8000/api/users/1/ but I can't access list of users: 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.

Before this, I had my module urls like this:

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

and I had access to http://localhost:8000/api/users/ . Can someone please explain me what is the error I make?

Just make id optional as:

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

And in view:

def users(request, id=None)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM