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

2024-04-02

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

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

通过 post 方法发送此正文

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

I have

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'))
]

音乐/urls.py

from django.urls import path
from .views import ListSongsView


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

音乐/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

音乐/序列化器.py

from rest_framework import serializers
from .models import Songs


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

模型.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)

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

你需要ListCreateAPIView as ListView只有GET方法并且不允许POST method

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Django REST 框架中的 405“不允许方法 POST” 的相关文章

随机推荐