【问题标题】:django url fails with optional parametersdjango url 因可选参数而失败
【发布时间】:2013-08-05 16:38:29
【问题描述】:

下面是我的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/。谁能解释一下我犯了什么错误?

【问题讨论】:

  • 错误是直截了当的,没有一个 url 模式正在处理 ^users/$
  • @AshwiniChaudhary 我应该更改什么以使 id 参数可选?

标签: python django url


【解决方案1】:

只需将 id 设为可选:

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

并且在视图中:

def users(request, id=None)

【讨论】:

    猜你喜欢
    • 2014-12-02
    • 1970-01-01
    • 2018-10-18
    • 2015-11-02
    • 2021-09-22
    • 2014-12-31
    • 1970-01-01
    • 2012-12-30
    相关资源
    最近更新 更多