DRF接口POST请求被禁止 创建UserProfile返回detail:not found问题求助
问题1:接口提示Method POST not allowed 解决方案
- 确认POST请求路径是否正确:ModelViewSet的创建接口为列表路由(不带ID后缀),即应当往
http://localhost:8000/api/user/profile/发送POST请求,带ID后缀的路径默认仅支持GET/PUT/PATCH/DELETE方法,发送POST会被直接拒绝。 - 补充请求解析器:当前视图仅配置了
MultiPartParser,仅支持form-data格式的请求,若发送JSON格式请求会因无法解析被拦截,修改配置如下:
from rest_framework.parsers import MultiPartParser, JSONParser class UserProfileViewSet(viewsets.ModelViewSet): # 其余原有配置保持不变 parser_classes = (MultiPartParser, JSONParser)
- 修复序列化器继承错误:当前
UserProfileSerializer未继承DRF的ModelSerializer,无法正常工作,修改为:
from rest_framework import serializers class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = "__all__"
问题2:访问http://localhost:8000/api/user/profile/2返回detail:not found 解决方案
- 该路径对应查询
UserProfile表中user_id=2的单条记录,返回404的核心原因是user_id=2的用户尚未创建对应的UserProfile数据,记录不存在。 - 若需要实现访问该路径时自动创建对应用户的
UserProfile,可重写视图的retrieve方法:
from rest_framework.response import Response from rest_framework import status class UserProfileViewSet(viewsets.ModelViewSet): # 其余原有配置保持不变 def retrieve(self, request, *args, **kwargs): try: instance = self.get_object() serializer = self.get_serializer(instance) return Response(serializer.data) except: user_id = kwargs.get('user') # 先校验对应用户是否存在,避免外键报错 if not User.objects.filter(user_id=user_id).exists(): return Response({"detail": "用户不存在"}, status=status.HTTP_400_BAD_REQUEST) profile = UserProfile.objects.create(user_id=user_id) serializer = self.get_serializer(profile) return Response(serializer.data, status=status.HTTP_201_CREATED)
注意:如果需要直接通过带ID的路径发送POST创建
UserProfile,可额外重写视图的create方法或新增自定义路由映射。
内容的提问来源于stack exchange,提问作者user11751463
相关产品推荐
相关产品推荐

