405 “Method POST is not allowed” in Django REST framework

半城伤御伤魂 提交于 2021-02-10 19:53:52

问题


I'm using Django REST framework to implement Get, Post api methods, and I got GET to work properly. However, when sending a post request, it's showing 405 error below. What am I missing here?

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

Sending this body via post method

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

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)

回答1:


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

you need ListCreateAPIView as ListView has only GET method and doesnt allow POST method




回答2:


Good Day

generics.ListAPIView is not allowed to POST it is only GET. If you want to allow GET and POST. You can use generics.ListCreateAPIView heres the documentation

on your 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


来源:https://stackoverflow.com/questions/53588539/405-method-post-is-not-allowed-in-django-rest-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!