405在Django REST框架中“不允许方法POST"
问题描述:
我正在使用Django REST框架来实现Get,Post api方法,并且GET可以正常工作.但是,在发送发布请求时,下面显示405错误.我在这里想念什么?
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."}
通过post方法发送此正文
Sending this body via post method
{
"title": "abc"
"artist": "abc"
}
我有
api/urls.py
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
music/urls.py
from django.urls import path
from .views import ListSongsView
urlpatterns = [
path('songs/', ListSongsView.as_view(), name="songs-all")
]
music/views.py
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
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
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)
答
class ListSongsView(generics.ListCreateAPIView):
"""
Provides a get method handler.
"""
queryset = Songs.objects.all()
serializer_class = SongsSerializer
您需要 ListCreateAPIView
,因为 ListView
仅具有 GET
方法,并且不允许 POST
方法
you need ListCreateAPIView
as ListView
has only GET
method and doesnt allow POST
method