1

I'm using Django Rest Framework for API and I faced this problem. In views.py my class inherits from ModelViewSet, but for some reason it doesn't allow making a POST request. For frontend I'm using React JS and I make a POST request from there. And in the end I'm getting an error like this: POST http://127.0.0.1:8000/api/software/3/ 405 (Method Not Allowed).

Here's views.py:

from rest_framework.viewsets import ModelViewSet

from .serializers import (
    CategorySerializer,
    SoftwareSerializer,
    SoftwareListRetrieveSerializer,
    CategoryDetailSerializer,
    CustomPaginatorSerializer
)
from ..models import Category, Software


class CategoryViewSet(ModelViewSet):

    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    pagination_class = None

    action_to_serializer = {
        "retrieve": CategoryDetailSerializer,
    }

    def get_serializer_class(self):
        return self.action_to_serializer.get(
            self.action,
            self.serializer_class
        )


class SoftwareViewSet(ModelViewSet):

    queryset = Software.objects.all()
    serializer_class = SoftwareSerializer
    pagination_class = CustomPaginatorSerializer

    action_to_serializer = {
        "list": SoftwareListRetrieveSerializer,
        "retrieve": SoftwareListRetrieveSerializer
    }

    def get_serializer_class(self):
        return self.action_to_serializer.get(
            self.action,
            self.serializer_class
        )

Here's urls.py:

from rest_framework import routers
from .views import CategoryViewSet, SoftwareViewSet

router = routers.SimpleRouter()
router.register('category', CategoryViewSet, basename='category')
router.register('software', SoftwareViewSet, basename='software')

urlpatterns = []
urlpatterns += router.urls
Albert
  • 95
  • 9

2 Answers2

1

http://127.0.0.1:8000/api/software/3/ , it looks like a detail of a data, you can only use PUT or Patch in details, no POST method is allowed.

San Tack
  • 74
  • 4
  • `PUT` doesn't work, throws an error: PUT 127.0.0.1:8000/api/software/3 400 (Bad Request) – Albert Mar 22 '21 at 09:26
  • 1
    PUT doesn't work maybe just because you didn't provide a full data for it to update, PUT is fully-update operation while PATCH is partial-update operation. – San Tack Mar 24 '21 at 01:41
0

This error is because the url http://127.0.0.1:8000/api/software/3/ is calling the retrieve method and this method must be called through GET.

Tiki
  • 760
  • 1
  • 8
  • 16