我一直在研究 Django 的視圖集和路由器檔案,但我不知道如何設定路由來訪問視圖集上的方法。
例如,這是我的 urls.py:
from rest_framework.routers import DefaultRouter
from users.views import (UserViewSet, testing)
router = DefaultRouter()
router.register(r"users", UserViewSet, basename="users")
urlpatterns = [
path('testing', testing)
]
然后這是我用戶目錄中的視圖檔案
@csrf_exempt
class UserViewSet:
def create(self):
return JsonResponse({
'the create endpoint'
})
@csrf_exempt
def testing(request):
return JsonResponse({
"title": "My json res"
})
使用郵遞員,我可以訪問端點 example.com/testing 并注銷 json 回應。但是,我嘗試點擊 example.com/users/create 并得到 404。我認為在basename向路由器注冊視圖集時的屬性會將類中的所有方法分組到該路由路徑下,然后這些方法都將是他們自己的終點。我是否錯誤地考慮了這一點?任何幫助都會很可愛,因為我是 Django 的新手。我主要完成了 Express 和 Laravel。謝謝!
uj5u.com熱心網友回復:
您沒有將路由器轉換為urlpatterns串列,因此無論如何您都無法訪問您的視圖集。
要轉換路由器:
from rest_framework.routers import DefaultRouter
from users.views import (UserViewSet, testing)
router = DefaultRouter()
router.register(r"users", UserViewSet, basename="users")
urlpatterns = [
path('testing', testing),
*router.urls,
]
在Django Rest Framework 中,視圖集的create方法在POST對特定 uri的請求期間執行。在您的情況下,此 uri 將是/users.
如果你想添加一個在 at 觸發的額外方法/users/create,你需要使用action裝飾器:
from rest_framework import viewsets
from rest_framework.response import JsonResponse
class UserViewSet(viewsets.ViewSet):
@action(methods=['GET'], url_path='create')
def my_custom_action(self):
return JsonResponse({
'the create endpoint'
})
由于create是 DRF 視圖集上的保留方法,因此您需要將該方法命名為其他名稱(在示例中為my_custom_action),并相應地設定url_path引數。
如果省略url_path,路徑將默認為方法的名稱,例如。/users/my_custom_action.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/351086.html
上一篇:型別錯誤:預期的str、bytes或os.PathLike物件,而不是Django中的JpegImageFile(或PngImageFile)
