【问题标题】:Django-Rest-Framework: router not workingDjango-Rest-Framework:路由器不工作
【发布时间】:2015-10-06 14:40:42
【问题描述】:

我有这个基本网址文件:

url(r'^locations/', include('locations.urls')),

locations.urls.py 应用程序中,我有以下网址引用:

url(r'^/?$', LocationList.as_view()),
url(r'^(?P<pk>[a-zA-Z0-9\-\$]+)/?$', LocationDetail.as_view()),
url(r'services/?$', LocationServiceseList.as_view()),
url(r'services/(?P<service_id>[a-zA-Z0-9\-\$]+)/?$', LocationServicesDetail.as_view()),

对于上面的 url 参考我想用户 routers 的 Django-Rest-framework

对于locations/services/,我从 DRF 创建了 GenericViewSet,我尝试路由器成功地在 location.urls 中进行了以下更改:

router = routers.SimpleRouter()
router.register(r'services', LocationServiceSet)

url(r'^/?$', LocationList.as_view()),
url(r'^(?P<vehicle_id>[a-zA-Z0-9\-\$]+)/?$', LocationDetail.as_view()),
url(r'^', include(router.urls)),

现在我想为/locations/ 端点创建路由器并进行以下更改

router = routers.SimpleRouter()
router.register(r'services', LocationServiceSet)
router.register(r'', LocationSet)


url(r'^', include(router.urls)),

虽然/locations/services/ 工作正常,但使用堆栈跟踪显示 /locations/ 得到 404:

^locations/ ^ ^services/$ [name='locationsservice-list']
^locations/ ^ ^services/(?P<pk>[^/.]+)/$ [name='locationsservice-detail']
^locations/ ^ ^/$ [name='locations-list']
^locations/ ^ ^/(?P<pk>[^/.]+)/$ [name='locations-detail']

【问题讨论】:

    标签: django-rest-framework


    【解决方案1】:

    这是因为LocationSetrouter.register() 函数的空字符串prefix 参数而发生的。

    当您使用空字符串'' 作为prefix 来注册路由器时,它会生成以下网址。 (注意 url 中的双斜杠

    locations//$ # double slash in urls
    locations//(?P<pk>[^/.]+)/$ # double slash in urls 
    

    要解决这个问题,您需要在基本 urls 文件中定义并注册此路由器,而不是 locations/urls.py,前缀值为 locations

    # base urls.py
    router = routers.SimpleRouter() 
    router.register(r'locations', LocationSet)
    
    ...
    url(r'^locations/', include('locations.urls')), # include app urls
    url(r'^', include(router.urls)), # include router urls
    

    另一种解决方案是在locations/urls.py 中为LocationSet 注册路由器时使用非空字符串作为prefix

    【讨论】:

      猜你喜欢
      • 2015-09-26
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 2015-01-23
      • 2020-10-07
      相关资源
      最近更新 更多