user10737394
user10737394

Reputation: 107

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

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)

Upvotes: 5

Views: 10618

Answers (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

Upvotes: 0

Exprator
Exprator

Reputation: 27503

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

Upvotes: 4

Related Questions