简体   繁体   English

POST 返回“详细信息”:“不允许使用方法 \"GET\"。”

[英]POST returns "detail": "Method \"GET\" not allowed."

The way the project works is there should be a random code that is given in creating a room (avoiding duplicates and the guessing a code that isn't taken) and the host should create their own name.该项目的工作方式是在创建房间时应该有一个随机代码(避免重复和猜测未被使用的代码),并且主持人应该创建自己的名字。

In the files, I've created the room and generated a random code that should be given when creating a room, but I receive an HTTP 405 Method Not Allowed.在文件中,我创建了房间并生成了创建房间时应提供的随机代码,但我收到 HTTP 405 方法不允许。 I'm attempting to POST and not GET so I'm confused as to why that's happening;我正在尝试 POST 而不是 GET,所以我对为什么会这样感到困惑; and the other parameters (code and host) do not show up.其他参数(代码和主机)不显示。 I assumed the code and host key would show up in the create method, but it doesn't.我假设代码和主机密钥会出现在创建方法中,但事实并非如此。 I would also like to add that I receive and Integrity Error regardless of changing the serializer to add id, code, and host to the serializer or if I leave the code the way it is in the screenshots.我还想补充一点,无论更改序列化程序以将 id、代码和主机添加到序列化程序,还是将代码保留为屏幕截图中的样子,我都会收到完整性错误。

在此处输入图像描述

models.py模型.py

from django.db import models
import random
import string

# Create your models here.

def code():
    """
    function randomly creates room access code
    """
    length = 7

    while True:
        code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))
        if Room.objects.filter(code=code).count() == 0:
            break

        return code
        
class Room(models.Model):
    """
    sets up room requirements and stores it as a model
    """
    code            = models.CharField(max_length=10, default=code,
                                        unique=True)
    host            = models.CharField(max_length=50, unique=True)
    guest_can_pause = models.BooleanField(null=False, default=False)
    votes_to_skip   = models.IntegerField(null=False, default=1)
    created_at      = models.DateTimeField(auto_now_add=True)

serializers.py序列化程序.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')

views.py视图.py

from django.shortcuts import render
from .models import Room
from .serializers import RoomSerializer, CreateRoomSerializer, UpdateRoomSerializer
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import generics, status


# Create your views here.

class RoomView(generics.ListAPIView):
    """
    collects all parameters from a serializer to show an existing room
    """
    queryset = Room.objects.all()
    serializer_class = RoomSerializer


class CreateRoomView(APIView):
    """
    creates a room using the POST method and accesses the serializer for the
    parameters
    """
    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['guest_can_pause']
            votes_to_skip = serializer.data['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()
                return Response(RoomSerializer(room).data, status=status.HTTP_201_CREATED)

            
        return Response({'Bad Request': 'Invalid data...'}, status=status.HTTP_400_BAD_REQUEST)

The POST request in POSTMAN can get converted to GET during redirects and give you HTTP 405 error: { "detail": "Method "GET" not allowed." POSTMAN 中的 POST 请求可以在重定向期间转换为 GET,并给您 HTTP 405 错误:{“详细信息”:“方法“GET”不允许。” } }

. . To avoid this you can go to the Setting (near Params, Auth.. ) in the request and click OFF to ON below items:为避免这种情况,您可以 go 到请求中的设置(靠近 Params,Auth.. ),然后单击 OFF 到 ON 下面的项目:

Follow original HTTP Method -> click ON Redirect with the original HTTP method instead of the default behavior of redirecting with GET.遵循原始 HTTP 方法 -> 单击 ON Redirect 使用原始 HTTP 方法而不是使用 GET 重定向的默认行为。

Follow Authorization header -> click ON Retain authorization header when a redirect happens to a different hostname. Follow Authorization header -> click ON Retain authorization header 当重定向发生到不同的主机名时。

It's actually due to the first request your browser makes to your server when you open the current URL and it is a get request because of which server response as getting if not allowed.这实际上是由于您的浏览器在您打开当前 URL 时向您的服务器发出的第一个请求,这是一个获取请求,因为如果不允许,则服务器响应为获取。

If you still want to have a get method try to use modelViewset they are amazing and very flexible go through this doc.如果您仍然想要一个 get 方法,请尝试使用 modelViewset,通过此文档,它们非常棒且非常灵活 go。 https://www.django-rest-framework.org/api-guide/viewsets/ https://www.django-rest-framework.org/api-guide/viewsets/

Instead of this class CreateRoomView(APIView): try this class CreateRoomView(generics.ListCreateApiView): if you want get and post method to work with the view.而不是这个class CreateRoomView(APIView):试试这个class CreateRoomView(generics.ListCreateApiView):如果你想要 get 和 post 方法来处理视图。 And if you only want post method than class CreateRoomView(generics.CreateAPIView):如果您只想要发布方法而不是class CreateRoomView(generics.CreateAPIView):

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 "detail": "方法 \\"POST\\" 不允许。" - "detail": "Method \"POST\" not allowed." { "detail": "方法 \\"GET\\" 不允许。" } - { "detail": "Method \"GET\" not allowed." } DRF:“详细信息”:“方法\\” GET \\“不允许。” - DRF: “detail”: “Method \”GET\“ not allowed.” "detail": "方法 \\"GET\\" 不允许。" 在 TokenAuthentication Django 休息框架中 - "detail": "Method \"GET\" not allowed." in TokenAuthentication Django rest framework django“详细信息”:“方法\\”GET\\“不允许。” (一对多关系) - django “detail”: “Method \”GET\“ not allowed.” (one to many relationship) "detail": "方法 \"GET\" 不允许。" Django Rest 框架 - "detail": "Method \"GET\" not allowed." Django Rest Framework “详细信息”:“方法 \\”GET\\” 不允许。在 Django 中调用端点 - “detail”: “Method \”GET\" not allowed. on calling endpoint in django “详细信息”:“方法 \”GET\“ 不允许。” Django Rest 框架 - “detail”: “Method \”GET\“ not allowed.” Django Rest Framework 不允许的方法。 Flask接收GET而不是POST - Method Not Allowed. Flask receives GET instead of POST Restangular删除不工作(是:DJANGO:{“detail”:“方法'删除'不允许。”}) - Restangular remove not working (was: DJANGO: {“detail”: “Method 'DELETE' not allowed.”})
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM