Метод \"POST\" не разрешен. Фреймворк для отдыха Django

Я не знаю, после определенного момента часть моего API перестала работать. Итак, я написал apiview и у него есть функция post, но когда я стучусь в конечную точку я получаю ошибку, что метод POST не разрешен, но другие части API работают нормально Так что у меня определенно что-то не так с postview.

project.urls

from django.contrib import admin
from django.urls import path, include
from rest_framework_simplejwt import views as jwt_views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/v1/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/v1/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),
    path('api/v1/', include('authentification.urls')),
    path('api/v1/', include('posts.urls')),  # This includes the posts app URLs
    path('api/v1/payments/', include('payments.urls')),
    path('api/v1/support/', include('support.urls')),
]

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

posts.urls

from django.urls import path
from .views import Lenta_View, Post_View, Profile_View, Settings_View, Like_View, Posts_search, Bookmark_View, Separated_lenta

urlpatterns = [
    path('', Lenta_View.as_view(), name='lenta'),
    path('<slug:filter>/', Separated_lenta.as_view(), name='lenta'),
    path('posts/', Post_View.as_view(), name='post_list_create'),  
    path('posts/<int:id>/', Post_View.as_view(), name='post_detail'), 
    path('profile/', Profile_View.as_view(), name='profile_mine'),
    path('profile/<slug:username>/', Profile_View.as_view(), name='profile_other'),
    path('settings/', Settings_View.as_view(), name='settings'),
    path('like/', Like_View.as_view(), name='like_all'),
    path('like/<int:id>/', Like_View.as_view(), name='like_add'),
    path('search', Posts_search.as_view(), name='search'),
    path('bookmarks/', Bookmark_View.as_view(), name='bookmark_list'),
    path('bookmarks/<int:id>/', Bookmark_View.as_view(), name='bookmark_add'),
]

Post_View

class Post_View(APIView):
    permission_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser]

    def get(self, request, *args, **kwargs):
        id = kwargs.get("id")
        user = request.user
        if id is None:
            return Response({'message': "You haven't provided an ID"}, status=status.HTTP_400_BAD_REQUEST)
        
        post_obj = get_object_or_404(FoodPost, id=id)
        if post_obj.is_public ==False and post_obj.created_by !=user:
            return Response({'message': "sorry it`s private meal"}, status=status.HTTP_400_BAD_REQUEST)
        ser = FPost_serializer(post_obj, context={'request': request})
        return Response({'data': ser.data}, status=status.HTTP_200_OK)

    def post(self, request):
        data = request.data
        user = request.user

        post_ser = FPost_serializer(data=data, context={'request': request})
        post_ser.is_valid(raise_exception=True)
        post_ser.save(created_by=user)
        return Response({'data': post_ser.data}, status=status.HTTP_201_CREATED)

    def patch(self, request, *args, **kwargs):
        data = request.data
        user = request.user

        id = kwargs.get("id")
        if id is None:
            return Response({'message': "You haven't provided an ID"}, status=status.HTTP_400_BAD_REQUEST)
        
        post_obj = get_object_or_404(FoodPost, id=id)

        if post_obj.created_by != user:
            return Response({'message': "You do not have permission to edit this post"}, status=status.HTTP_403_FORBIDDEN)

        if 'images' in data:
            images = request.FILES.getlist('images')
            for image in images:
                ImagePost.objects.create(post=post_obj, image=image)
        
        post_ser = FPost_serializer(post_obj, data=data, partial=True, context={'request': request})
        post_ser.is_valid(raise_exception=True)
        post_ser.save()
        return Response({'post': post_ser.data, 'message': 'Post updated successfully'}, status=status.HTTP_202_ACCEPTED)
    
    def put(self,request,*args,**kwargs):
        data = request.data
        user= request.user

        id = kwargs.get("id",None)
        if id is None:
            return Response({'message': "You haven't provided an ID"}, status=status.HTTP_400_BAD_REQUEST)
        post_obj = get_object_or_404(FoodPost, id=id)
        com_ser = Comment_serializer(data=data)
        com_ser.is_valid(raise_exception=True)
        com_ser.save(post_obj=post_obj,commented_by=user)
        return Response({'comment': com_ser.data, 'message': 'comment uploaded successfully'}, status=status.HTTP_202_ACCEPTED)

и я получаю такую ошибку:

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

на конечной точке http://127.0.0.1:8000/api/v1/posts/ с телом в post.

Проблема заключается в ваших URL-адресах в posts.urls. Ваш Post_View используется как для создания новых постов, так и для просмотра подробностей о них. Однако URL для создания постов (posts/) и URL для просмотра деталей поста (posts/int:id/) пересекаются. Эта путаница заставляет Django блокировать POST-запросы, что приводит к ошибке "Метод POST не разрешен".

Разделить URL-адреса для просмотра списка/создания и детального просмотра

urlpatterns = [
    path('', Lenta_View.as_view(), name='lenta'),
    path('filtered/<slug:filter>/', Separated_lenta.as_view(), name='lenta'),
    path('posts/', Post_View.as_view(), name='post_list_create'),  # URL for listing and creating posts
    path('posts/<int:id>/', Post_View.as_view(), name='post_detail'),  # URL for post details
    path('profile/', Profile_View.as_view(), name='profile_mine'),
    path('profile/<slug:username>/', Profile_View.as_view(), name='profile_other'),
    path('settings/', Settings_View.as_view(), name='settings'),
    path('like/', Like_View.as_view(), name='like_all'),
    path('like/<int:id>/', Like_View.as_view(), name='like_add'),
    path('search/', Posts_search.as_view(), name='search'),
    path('bookmarks/', Bookmark_View.as_view(), name='bookmark_list'),
    path('bookmarks/<int:id>/', Bookmark_View.as_view(), name='bookmark_add'),
]

Модификация Post_View для работы с различными методами HTTP:

class Post_View(APIView):
    permission_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser]

    def get(self, request, *args, **kwargs):
        id = kwargs.get("id")
        user = request.user
        if id is None:
            return Response({'message': "You haven't provided an ID"}, status=status.HTTP_400_BAD_REQUEST)
        
        post_obj = get_object_or_404(FoodPost, id=id)
        if post_obj.is_public == False and post_obj.created_by != user:
            return Response({'message': "sorry it`s private meal"}, status=status.HTTP_400_BAD_REQUEST)
        ser = FPost_serializer(post_obj, context={'request': request})
        return Response({'data': ser.data}, status=status.HTTP_200_OK)

    def post(self, request):
        data = request.data
        user = request.user

        post_ser = FPost_serializer(data=data, context={'request': request})
        post_ser.is_valid(raise_exception=True)
        post_ser.save(created_by=user)
        return Response({'data': post_ser.data}, status=status.HTTP_201_CREATED)

    def patch(self, request, *args, **kwargs):
        data = request.data
        user = request.user

        id = kwargs.get("id")
        if id is None:
            return Response({'message': "You haven't provided an ID"}, status=status.HTTP_400_BAD_REQUEST)
        
        post_obj = get_object_or_404(FoodPost, id=id)

        if post_obj.created_by != user:
            return Response({'message': "You do not have permission to edit this post"}, status=status.HTTP_403_FORBIDDEN)

        if 'images' in data:
            images = request.FILES.getlist('images')
            for image in images:
                ImagePost.objects.create(post=post_obj, image=image)
        
        post_ser = FPost_serializer(post_obj, data=data, partial=True, context={'request': request})
        post_ser.is_valid(raise_exception=True)
        post_ser.save()
        return Response({'post': post_ser.data, 'message': 'Post updated successfully'}, status=status.HTTP_202_ACCEPTED)
    
    def put(self, request, *args, **kwargs):
        data = request.data
        user = request.user

        id = kwargs.get("id", None)
        if id is None:
            return Response({'message': "You haven't provided an ID"}, status=status.HTTP_400_BAD_REQUEST)
        post_obj = get_object_or_404(FoodPost, id=id)
        com_ser = Comment_serializer(data=data)
        com_ser.is_valid(raise_exception=True)
        com_ser.save(post_obj=post_obj, commented_by=user)
        return Response({'comment': com_ser.data, 'message': 'comment uploaded successfully'}, status=status.HTTP_202_ACCEPTED)
Вернуться на верх