Home > Software engineering >  django rest framework post method not allowed
django rest framework post method not allowed

Time:10-20

I am creating an api and no idea why post method not allowed on any url.

views

class MessagesView(APIView):

    permission_classes = (IsAuthenticated,)

    def post(self, request):
        serializer = MessageSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

chat.urls

urlpatterns = [
    path("<str:pk>/", ChatDetail.as_view()),
    path("messages/", MessagesView.as_view()),
]

response

{
    "detail": "Method \"POST\" not allowed."
}

I am providing the token for the request, so isAuthenticated does not do anything wrong here.

CodePudding user response:

Your first pattern will fire if you visit messages/. Indeed, its <str:pk> parameter matches any string (with at least one character and without slashes). But messages is thus also matched with this view.

What you can do is swap the places of the two urls, then calling messages/ will fire the correct view:

urlpatterns = [
    #       ↓ messages first
    path('messages/', MessagesView.as_view()),
    path('<str:pk>/', ChatDetail.as_view()),
]

If pk is an integer, you can further restrict the pk with the <int:…> path converter:

urlpatterns = [
    path('messages/', MessagesView.as_view()),
    path('<int:pk>/', ChatDetail.as_view()),
]
  • Related