我是第一次学习django restframework,有一段时间无法调试这个错误,请帮助调试这个问题。谢谢!
HTTP 405 Method Not Allowed
Allow: POST, OPTIONS
Content-Type: application/json
Vary: Accept
{
"detail": "Method "GET" not allowed."
}
这是我的视图代码。py
from django.shortcuts import render
from rest_framework import generics, status
from .serializers import RoomSerializer, CreateRoomSerializer
from .models import Room
from rest_framework.views import APIView
from rest_framework.response import Response
class RoomView(generics.ListAPIView):
queryset = Room.objects.all()
serializer_class = RoomSerializer
class CreateRoomView(APIView):
serializer_class = CreateRoomSerializer
def post(self, request, format=None):
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
guest_can_pause = serializer.data.get('guest_can_pause')
votes_to_skip = serializer.data.get('votes_to_skip')
host = self.request.session.session_key
queryset = Room.objects.filter(host=host)
if queryset.exists():
room = queryset[0]
room.guest_can_pause = guest_can_pause
room.votes_to_skip = votes_to_skip
room.save(update_fields=['guest_can_pause', 'votes_to_skip'])
return Response(RoomSerializer(room).data, status=status.HTTP_200_OK)
else:
room = Room(host=host, guest_can_pause=guest_can_pause,
votes_to_skip=votes_to_skip)
room.save()
这根本不是问题。因为当你在浏览器中点击url时,最初它会调用GET方法。但你还没有在APIView中实现它。为了安全起见,按照约定,您需要为所有实例的列表添加一个get方法。如,
class CreateRoomView(APIView):
def get(self, request, format=None):
rooms = Room.objects.all()
serializer = RoomSerializer(rooms, many=True)
return Response(serializer.data)
def post(self, request, format=None):
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
serializer = CreateRoomSerializer(data=request.data)
if serializer.is_valid():
guest_can_pause = serializer.data.get('guest_can_pause')
votes_to_skip = serializer.data.get('votes_to_skip')
host = self.request.session.session_key
queryset = Room.objects.filter(host=host)
if queryset.exists():
room = queryset[0]
room.guest_can_pause = guest_can_pause
room.votes_to_skip = votes_to_skip
room.save(update_fields=['guest_can_pause', 'votes_to_skip'])
return Response(RoomSerializer(room).data, status=status.HTTP_200_OK)
else:
room = Room(host=host, guest_can_pause=guest_can_pause,
votes_to_skip=votes_to_skip)
room.save()
如果您希望您的类能够处理get请求,则需要在CreateRoomView类中使用get方法
class CreateRoomView(APIView):
serializer_class = CreateRoomSerializer
def get(self, request, format=None):
...
如果您在客户端尝试发出POST请求时遇到此错误,那么请确保您正在向服务器发出POST请求而不是GET请求