Django-Rest-Framework:路由器无法正常工作

时间:2015-10-06 14:40:42

标签: django-rest-framework

我有这个基本网址文件:

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

locations.urls.py app我有以下网址引用:

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

for locations/services/我从DRF创建了GenericViewSet,我尝试路由器成功地在locations.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)),

使用stacktrace获取/locations/的404显示虽然/locations/services/正常工作:

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

1 个答案:

答案 0 :(得分:0)

由于prefix的{​​{1}}参数为router.register(),因此正在发生

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

prefix

要解决此问题,您需要在基本网址文件中定义并注册此路由器,而不是locations//$ # double slash in urls locations//(?P<pk>[^/.]+)/$ # double slash in 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 中为prefix注册路由器时,将非空字符串用作LocationSet