use*_*394 5 python django django-rest-framework
我正在使用 Django REST 框架来实现 Get、Post api 方法,并且 GET 可以正常工作。但是,当发送 post 请求时,会显示下面的 405 错误。我在这里缺少什么?
405 Method Not Allowed
{"detail":"Method \"POST\" not allowed."}
Run Code Online (Sandbox Code Playgroud)
通过 post 方法发送此正文
{
"title": "abc"
"artist": "abc"
}
Run Code Online (Sandbox Code Playgroud)
我有
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'))
]
Run Code Online (Sandbox Code Playgroud)
音乐/urls.py
from django.urls import path
from .views import ListSongsView
urlpatterns = [
path('songs/', ListSongsView.as_view(), name="songs-all")
]
Run Code Online (Sandbox Code Playgroud)
音乐/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
Run Code Online (Sandbox Code Playgroud)
音乐/序列化器.py
from rest_framework import serializers
from .models import Songs
class SongsSerializer(serializers.ModelSerializer):
class Meta:
model = Songs
fields = ("title", "artist")
Run Code Online (Sandbox Code Playgroud)
模型.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)
Run Code Online (Sandbox Code Playgroud)
class ListSongsView(generics.ListCreateAPIView):
"""
Provides a get method handler.
"""
queryset = Songs.objects.all()
serializer_class = SongsSerializer
Run Code Online (Sandbox Code Playgroud)
你需要ListCreateAPIViewasListView只有GET方法并且不允许POST方法
| 归档时间: |
|
| 查看次数: |
10158 次 |
| 最近记录: |