找不到页面 Django Restframework

问题描述 投票:0回答:1

我正在尝试在 django 中编写一个 API 以从 url 获取用户评论

我的API是:

class ListSpecificUserCommentsApiView(APIView):
    authentication_classes = [authentication.TokenAuthentication]
    permission_classes = [permissions.AllowAny]
    
    def get(self, request: HttpRequest, user) -> Response:
        username: User = User.objects.get(id=user.id)
        comments: Comment = Comment.objects.filter(user=username)
        serialized_comments: CommentModelSerializer = CommentModelSerializer(instance=comments, many=True).data
        
        return Response(serialized_comments)

还有我的

urls.py

urlpatterns = [
    path(
        route='users',
        view=views.ListUsersApiView.as_view(),
        name='users',
    ),
    path(
        route='comments/<user>',
        view=views.ListSpecificUserCommentsApiView.as_view(),
        name='user-comments',
    ),
]

我仍然面临这个页面未找到错误

我尝试将用户作为 DRF 中的数据传递

Response
,如下面的代码:

class ListSpecificUserCommentsApiView(APIView):
    authentication_classes = [authentication.TokenAuthentication]
    permission_classes = [permissions.AllowAny]
    
    def get(self, request: HttpRequest, user) -> Response:
        username: User = User.objects.get(id=user.id)
        comments: Comment = Comment.objects.filter(user=username)
        serialized_comments: CommentModelSerializer = CommentModelSerializer(instance=comments, many=True).data
        
        return Response(serialized_comments, data=user)

但是没有成功

django api django-models django-rest-framework django-views
1个回答
0
投票

我没有发现代码有任何问题。 一个可疑的部分是 url 路径中没有最后一个“/”。

urlpatterns = [
    path(
        route='users',
        view=views.ListUsersApiView.as_view(),
        name='users',
    ),
    path(
        route='comments/<user>',
        view=views.ListSpecificUserCommentsApiView.as_view(),
        name='user-comments',
    ),
]

如果通过在上述路径末尾添加“/”来发送请求,则会出现页面未找到错误。

将最后一个“/”添加到每个路径,然后重试!

urlpatterns = [
    path(
        route='users/',
        view=views.ListUsersApiView.as_view(),
        name='users',
    ),
    path(
        route='comments/<user>/',
        view=views.ListSpecificUserCommentsApiView.as_view(),
        name='user-comments',
    ),
]
© www.soinside.com 2019 - 2024. All rights reserved.