HTTP 405 Method Not Allowed Django

aelbi1ox  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(126)

我正在尝试创建一个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

3pmvbmvn

3pmvbmvn1#

希望这个答案对你有用

# views.py
from django.shortcuts import render
from rest_framework import generics, status
from rest_framework.exceptions import ValidationError

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
#    serializers = CreateRoomSerializer

# The problematic API View
class RoomAPIView(APIView):
    serializer_class = RoomSerializer

    def get(self, request, format=None):
        queryset = Room.objects.all()
        data = RoomSerializer(data=queryset, many=True)

        return Response(data=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)

        try:
            serializer.is_valid(raise_exception=True)
        except ValidationError:
            return Response({'Bad Request': 'Invalid data...'}, status=status.HTTP_400_BAD_REQUEST)

        # Check if host already has a session
        host = self.request.session.session_key

        room, is_created = Room.objects.update_or_create(
            host=host,
            defaults={
                "guest_can_pause": serializer.data['guest_can_pause'],
                "votes_to_skip": serializer.data['votes_to_skip'],
            },
        )

        return Response(
            data=RoomSerializer(room).data,
            status=status.HTTP_201_CREATED,
        )

        # 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)

字符串
建议将APIView统一为一个

# urls.py
from django.urls import path
from . import views

# URLConf
urlpatterns = [
    path('api/rooms/', views.RoomAPIView.as_view()),
]


你可以在链接http://localhost:8000/api/rooms/GET & POST中看到API文档

相关问题