Django 休息框架问题
Posted
技术标签:
【中文标题】Django 休息框架问题【英文标题】:Django rest framework probleme 【发布时间】:2019-02-08 18:38:54 【问题描述】:这是我的代码:
from rest_framework import routers
from rest_framework.routers import DefaultRouter
from .api import ListViewSet, CardViewSet
router = DefaultRouter()
router.register(r'lists', ListViewSet,'lists')
router.register(r'cards', CardViewSet, 'cards')
urlpatterns = router.urls
但是当我运行服务器时,我得到了这个错误:
Page not found (404) Request Method:
GET Request URL: http://localhost:8000/scrumboard/cards Using the URLconf defined in djangularApp.urls, Django tried these URL patterns, in this order:
^admin/ ^$ ^scrumboard ^lists/$ [name='lists-list'] ^scrumboard
^lists\.(?P<format>[a-z0-9]+)/?$ [name='lists-list'] ^scrumboard
^lists/(?P<pk>[^/.]+)/$ [name='lists-detail'] ^scrumboard
^lists/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='lists-detail']
^scrumboard ^cards/$ [name='cards-list'] ^scrumboard
^cards\.(?P<format>[a-z0-9]+)/?$ [name='cards-list'] ^scrumboard
^cards/(?P<pk>[^/.]+)/$ [name='cards-detail'] ^scrumboard
^cards/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='cards-detail']
^scrumboard ^$ [name='api-root'] ^scrumboard
^\.(?P<format>[a-z0-9]+)/?$ [name='api-root']
The current path, scrumboard/cards, didn't match any of these.
您看到此错误是因为您的 Django 中有 DEBUG = True 设置文件。将其更改为 False,Django 将显示标准 404 页面。
【问题讨论】:
【参考方案1】:您似乎还没有注册网址,即您的project/urls.py
path('api/', include((router.urls), namespace='api')),
这意味着路径将以/api/cards
开头
或/scrumboard
path('scrumboard/', include((router.urls), namespace='scrumboard')),
那么你可以使用/scrumboard/cards
【讨论】:
【参考方案2】:您似乎忘记在scrumboard
网址后添加/,可能是您在其中包含路由器的网址。
这是可见的,因为 ^scrumboard ^cards/$
应该是 ^scrumboard/ ^cards/$
以匹配您期望的 url。
【讨论】:
以上是关于Django 休息框架问题的主要内容,如果未能解决你的问题,请参考以下文章
Django 测试休息框架:APIRequestFactory vs APIClient