405在Django REST框架中“不允许方法POST”

时间:2018-12-03 06:27:16

标签: python django django-rest-framework

我正在使用Django REST框架实现Get,Post api方法,并且GET可以正常工作。但是,在发送发布请求时,下面显示405错误。我在这里想念什么?

405 Method Not Allowed
{"detail":"Method \"POST\" not allowed."}

通过post方法发送此正文

{
    "title": "abc"
    "artist": "abc"
}

我有

api / urls.py

from django.contrib import admin
from django.urls import path, re_path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path('api/(?P<version>(v1|v2))/', include('music.urls'))
]

music / urls.py

from django.urls import path
from .views import ListSongsView


urlpatterns = [
    path('songs/', ListSongsView.as_view(), name="songs-all")
]

music / views.py

from rest_framework import generics
from .models import Songs
from .serializers import SongsSerializer


class ListSongsView(generics.ListAPIView):
    """
    Provides a get method handler.
    """
    queryset = Songs.objects.all()
    serializer_class = SongsSerializer

music / serializers.py

from rest_framework import serializers
from .models import Songs


class SongsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Songs
        fields = ("title", "artist")

models.py

from django.db import models

class Songs(models.Model):
    # song title
    title = models.CharField(max_length=255, null=False)
    # name of artist or group/band
    artist = models.CharField(max_length=255, null=False)

    def __str__(self):
        return "{} - {}".format(self.title, self.artist)

2 个答案:

答案 0 :(得分:1)

class ListSongsView(generics.ListCreateAPIView):
    """
    Provides a get method handler.
    """
    queryset = Songs.objects.all()
    serializer_class = SongsSerializer

您需要ListCreateAPIView,因为ListView仅具有GET方法,而不允许使用POST方法

答案 1 :(得分:0)

美好的一天

generics.ListAPIView不允许POST,而只是GET。如果要允许GET和POST。您可以使用generics.ListCreateAPIView继承https://github.com/aws/amazon-connect-streams

在您的music / views.py上

from rest_framework import generics
from .models import Songs
from .serializers import SongsSerializer


class ListSongsView(generics.ListCreateAPIView):
    """
    Provides a get method handler.
    """
    queryset = Songs.objects.all()
    serializer_class = SongsSerializer