9

我正在尝试使用 Django 2.0 项目设置 Django REST Framework,这意味着url(r'^something/' ...已替换为path(something/ ....

我正在尝试弄清楚如何设置我的rest_framework模式。

这就是我所拥有的:

router = routers.DefaultRouter()
router.register(r'regulations', api.RegulationViewSet)
router.register(r'languages', api.LanguageViewSet)


urlpatterns = [
    ...
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    ...
]

如果我去,http://127.0.0.1:8000/regulations我只会得到:

找不到页面 (404)

我应该如何设置我的urlpatterns

4

2 回答 2

15
urlpatterns = [
    ...
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    ...
]

path('', include(router.urls)),您一起可以获得:

http://127.0.0.1:8000/regulations/
http://127.0.0.1:8000/languages/

path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),

你可以得到:

http://127.0.0.1:8000/api-auth/{other paths}
于 2018-02-27T09:47:51.077 回答
3

注册后,router您必须将其包含在urlpatterns. @Ykh 建议的方式在技术上是正确的,但在内容方面却没有抓住重点。

urlpatterns = [
    # here you include your router
    path('', include(router.urls)),
    # here you include the authentication paths
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]

现在您将拥有以下路线:

http://localhost:8000/regulations/
http://localhost:8000/languages/

加:

http://localhost:8000/api-auth/{other paths}
于 2018-02-27T10:11:13.513 回答