Django REST Framework页面未找到:获取指定用户评论API报错
问题排查与解决
错误原因
- 路由格式不合法:Django的
path路由参数必须遵循<类型:变量名>的格式,你写的comments/<user>不符合规范,Django无法解析该参数,导致请求URL无法匹配到视图,触发404错误。 - 视图参数处理错误:即使路由能匹配,直接调用
user.id也是错误的——路由传递的参数是字符串或数字,并非User实例,会引发AttributeError。 - 无效的Response修改:给
Response添加data=user完全没用,Response的构造函数没有这个参数,这部分修改和404问题无关。
解决步骤
1. 修复路由配置
根据你想用的用户标识(ID或用户名),修改urls.py的路由规则:
用用户ID作为参数:
urlpatterns = [ path( route='users/', view=views.ListUsersApiView.as_view(), name='users', ), path( route='comments/<int:user_id>/', view=views.ListSpecificUserCommentsApiView.as_view(), name='user-comments', ), ]
用用户名作为参数:
urlpatterns = [ path( route='users/', view=views.ListUsersApiView.as_view(), name='users', ), path( route='comments/<str:username>/', view=views.ListSpecificUserCommentsApiView.as_view(), name='user-comments', ), ]
2. 修正视图逻辑
根据路由传递的参数,正确查询用户和评论,同时处理用户不存在的情况:
对应用户ID的视图:
from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication, permissions from .models import User, Comment from .serializers import CommentModelSerializer class ListSpecificUserCommentsApiView(APIView): authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.AllowAny] def get(self, request, user_id): # 用户不存在时直接返回404,避免抛出异常 user = get_object_or_404(User, id=user_id) comments = Comment.objects.filter(user=user) serializer = CommentModelSerializer(comments, many=True) return Response(serializer.data)
对应用户名的视图:
from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication, permissions from .models import User, Comment from .serializers import CommentModelSerializer class ListSpecificUserCommentsApiView(APIView): authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.AllowAny] def get(self, request, username): user = get_object_or_404(User, username=username) comments = Comment.objects.filter(user=user) serializer = CommentModelSerializer(comments, many=True) return Response(serializer.data)
3. 验证请求URL
修复后,请求URL需要对应路由规则,比如用用户ID的话,请求/comments/1/(假设用户ID为1),用用户名的话请求/comments/john/(假设用户名为john)。
内容的提问来源于stack exchange,提问作者Shervin.bdn
相关产品推荐
相关产品推荐

