我正在尝试创建一个APIView(www.example.com中的路径'create-room'urls.py),如果会话已经存在,则可以在其中编辑房间模型,如果会话不存在,则可以创建新的房间模型。在APIView中,this is what I am getting.我不知道为什么它说GET /api/create-room
,这导致了HTTP 405 Method Not Allowed
的错误。如何将请求更改为POST请求,如shown in the tutorial(将GET
改为POST /api/create-room
我的代码:
# views.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
# Create your views here.
class RoomView(generics.ListAPIView):
queryset = Room.objects.all()
serializer_class = RoomSerializer
# The problematic API View
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
# Check if host already has a session
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()
return Response(RoomSerializer(room).data, status=status.HTTP_201_CREATED)
return Response({'Bad Request': 'Invalid data...'}, status=status.HTTP_400_BAD_REQUEST)
# serializers.py
from rest_framework import serializers
from .models import Room
class RoomSerializer(serializers.ModelSerializer):
class Meta:
model = Room
fields = ('id', 'code', 'host', 'guest_can_pause',
'votes_to_skip', 'created_at')
class CreateRoomSerializer(serializers.ModelSerializer):
class Meta:
model = Room
fields = ('guest_can_pause', 'votes_to_skip')
# urls.py
from django.urls import path
from . import views
# URLConf
urlpatterns = [
path('room', views.RoomView.as_view()),
path('create-room', views.CreateRoomView.as_view())
]
我已经尝试将这段代码添加到视图中
def get(self, request, format=None):
queryset = Room.objects.all()
serializer = self.serializer_class()
return Response(serializer.data)
型
但是这个请求是一个GET请求,当我尝试在API视图上发出POST请求时,它会永远加载:This is where I try to make a POST request that loads forever的
1条答案
按热度按时间3pmvbmvn1#
希望这个答案对你有用
字符串
建议将APIView统一为一个
型
你可以在链接http://localhost:8000/api/rooms/GET & POST中看到API文档