gpt4 book ai didi

python - "detail": "Method\"GET\"not allowed." Django Rest Framework

转载 作者:行者123 更新时间:2023-12-03 20:27:43 32 4
gpt4 key购买 nike

我知道这个问题可能是重复的,但我尝试了很多解决方案,但无法理解。我完全按照本教程进行操作,但在“用户列表”页面上出现此错误。其他一切都很好。有人可以指出错误是什么吗?

class UserList(APIView):
"""
Create a new user. It's called 'UserList' because normally we'd have a get
method here too, for retrieving a list of all User objects.
"""

permission_classes = (permissions.AllowAny,)
http_method_names = ['get', 'head']

def post (self, request, format=None):
self.http_method_names.append("GET")

serializer = UserSerializerWithToken(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

编辑:
网址.py
from django.urls import include, path
from classroom.views.classroom import current_user, UserList
from .views import classroom, suppliers, teachers
urlpatterns = [path('', classroom.home, name='home'),
path('current_user/', current_user),
path('users/', UserList.as_view()),

编辑:

还是出现这个错误

err

最佳答案

您需要将 GET 端点 url 添加到您的 urls.py为了使用 GET 请求。您的 urls.py 中缺少 GET 网址,只需编辑您的 urls.py喜欢:

# urls.py

from django.urls import include, path
from classroom.views.classroom import current_user, UserList
from .views import classroom, suppliers, teachers

urlpatterns = [
path('', classroom.home, name='home'),
path('current_user/', current_user),
path('users/', UserList.as_view()),
path('users/<int:pk>/', UserList.as_view()),
]

而你需要实现 get您的 UserList 中的方法 View 如:

# views.py

class UserList(APIView):
"""
Create a new user. It's called 'UserList' because normally we'd have a get
method here too, for retrieving a list of all User objects.
"""

permission_classes = (permissions.AllowAny,)
http_method_names = ['get', 'head']


def get(self, request, format=None):
users = User.objects.all()
serializer = UserSerializerWithToken(users, many=True)
return Response(serializer.data)

def post(self, request, format=None):
self.http_method_names.append("GET")

serializer = UserSerializerWithToken(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

关于python - "detail": "Method\"GET\"not allowed." Django Rest Framework,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57302570/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com