【问题标题】:405 “Method POST is not allowed” in Django REST frameworkDjango REST 框架中的 405“不允许使用方法 POST”
【发布时间】:2019-05-04 10:32:37
【问题描述】:

我正在使用 Django REST 框架来实现 Get、Post api 方法,并且让 GET 正常工作。但是,在发送 post 请求时,它会在下面显示 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'))
]

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

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

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:
    class ListSongsView(generics.ListCreateAPIView):
        """
        Provides a get method handler.
        """
        queryset = Songs.objects.all()
        serializer_class = SongsSerializer
    

    你需要ListCreateAPIView,因为ListView只有GET方法并且不允许POST方法

    【讨论】:

      【解决方案2】:

      美好的一天

      generics.ListAPIView 不允许 POST,它只能是 GET。如果你想允许 GET 和 POST。您可以使用 generics.ListCreateAPIView 继承人 documentation

      在你的音乐/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
      

      【讨论】:

        猜你喜欢
        • 2016-03-29
        • 2020-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-05
        • 1970-01-01
        • 2018-06-04
        相关资源
        最近更新 更多