【问题标题】:Django REST Framework URLs with Django 2.0带有 Django 2.0 的 Django REST 框架 URL
【发布时间】:2018-08-06 21:34:14
【问题描述】:

我正在尝试使用 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

【问题讨论】:

  • url()没有被替换。它仍然有效。 path() 是一个替代。但是请注意,您似乎没有为 /regulations 定义 URL。
  • @DanielRoseman 但是他已经在router 注册了regulations。他需要在urlpatternsinclude 或通过连接:urlpatterns += router.urls 来实现它。

标签: django django-rest-framework django-2.0


【解决方案1】:
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}

【讨论】:

  • 这将导致http://localhost:8000/api-auth/regulationsrest_framework.urls 也是正确的,但它是针对 Django REST Framework 提供的身份验证路由。 routers.urls 应该包含在另一个路径下。
  • 那你应该去掉最后一句,加上解释。
【解决方案2】:

注册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}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-01
    • 2015-05-10
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多