kakakakakakakk
kakakakakakakk

Reputation: 519

django rest framework post method not allowed

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.

Upvotes: 1

Views: 418

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476493

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()),
]

Upvotes: 3

Related Questions