DJANGO: mixins.DestroyModelMixin delete - method not allowed

Viewed 3298

I have an API that returns list of all likes.

Here is model for likes:

class Like(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['user', 'post'], name='like_once')
        ]

Here is my view:

class likeList(mixins.CreateModelMixin, mixins.DestroyModelMixin, generics.ListAPIView):
    serializer_class = likeserializers

    def get_queryset(self):
        return Like.objects.all()

    def post(self, request, *args, **kwargs):
        try:
            return self.create(request, *args, **kwargs)
        except IntegrityError:
            content = {'error': 'IntegrityError'}
            return Response(content, status=status.HTTP_400_BAD_REQUEST)

    def destroy(self, request, *args, **kwargs):
        try:
            return self.destroy(request, *args, **kwargs)
        except IntegrityError:
            content = {'error': 'IntegrityError'}
            return Response(content, status=status.HTTP_400_BAD_REQUEST)

Here are my urls:

from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
from . import views as API_views

urlpatterns = [
    path('users/', API_views.userList.as_view(), name = 'users'),
    path('users/id=<int:id>/', API_views.userListbyID.as_view(), name = 'usersid'),
    path('posts/', API_views.postList.as_view(), name = 'post'),
    path('posts/id=<int:id>', API_views.postListbyID.as_view(), name = 'postid'),
    path('likes/', API_views.likeList.as_view(), name = 'likes'),
    path('likes/test/<int:id>', API_views.likeListbyID.as_view(), name = 'likesid'),
    path('likes/<int:id>', API_views.LikeCountView.as_view(), name='likecount'),
    path('follows/', API_views.followList.as_view(), name = 'follows'),
    path('follows/id=<int:id>', API_views.followListbyID.as_view(), name = 'followsid'),
]

if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.MEDIA_URL)

I call the delete api with json body {"user":userid,"post":postid}

however, I receive method Not Allowd (HTTP 405). Also I can see on the API page "Allow: GET, POST, HEAD, OPTIONS"

What am I doing wrong?

FYI: The get and create methods work as expected.

1 Answers

You need to use two different views for these operations. List and Create mixins do not require object pk but Destroy mixin does. You need to split Destroy mixin to another view as sampled in docs. If you do not supply pk to delete, the operation fails.

Related