我不知道,过了一段时间我的 API 部分就停止工作了。 所以我写了我的
apiview
并且它有post功能,但是当我敲一个端点时
我收到不允许 POST 方法的错误,但 API 的其他部分工作正常
所以我肯定有问题postview
。
项目.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'),
]
帖子_查看
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/ 端点上,正文位于帖子中。
问题出在 posts.urls 中的 URL。您的 Post_View 用于创建新帖子和查看帖子详细信息。但是,用于创建帖子的 URL (posts/) 和用于查看帖子详细信息的 URL (posts/int:id/) 重叠。这种混乱会导致 Django 阻止 POST 请求,从而导致“Method POST not allowed”错误。
将列表/创建和详细视图的 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)