Django DRF报'Response' object has no attribute 'user'错误如何解决
问题根源与解决方案
错误原因
你遇到的AttributeError: 'Response' object has no attribute 'user'错误核心来自两个逻辑错误:
- 序列化器的
create方法必须返回模型实例,但你在create、checkNotification、validateSubject中直接返回了Response对象,DRF会把这个返回的Response当做序列化器的instance属性,后续序列化读取user字段时,就会尝试访问Response.user,自然不存在这个属性。 get_queryset方法要求必须返回QuerySet类型,但你在未授权分支返回了Response对象,会导致所有调用该方法的逻辑出现类型错误。
另外你贴出的代码存在缩进错误,视图类的get_queryset、retrieve方法,序列化器的create等方法没有缩进进对应类中,实际运行时不会生效,需要先修正缩进。
修复步骤
1. 修正序列化器逻辑
序列化器仅负责数据校验和模型操作,所有Response返回都移到视图层,由DRF自动封装:
class CourseNotificationSerializer(serializers.ModelSerializer): class Meta: model = CourseNotification fields = '__all__' def create(self, validated_data): users = self.context['request'].user subject = validated_data['course'] if not users or not subject: raise serializers.ValidationError({"Invalid": "Subject could not be Invalid"}) # 检查是否已有通知,有就移除用户关联 exist_notify = CourseNotification.objects.filter(user=users, course=subject).first() if exist_notify: exist_notify.user.remove(users) exist_notify.save() return exist_notify # 检查是否有同课程的其他通知,有就添加当前用户关联 other_notify = CourseNotification.objects.filter(course=subject).exclude(user=users).first() if other_notify: other_notify.user.add(users) other_notify.save() return other_notify # 都不存在就新建通知 new_notify = CourseNotification.objects.create(course=subject) new_notify.user.add(users) new_notify.save() return new_notify
2. 修正视图层逻辑
删除get_queryset中返回Response的分支,你已经配置了IsAuthenticated权限,未登录用户会直接被拦截,不会走到该方法中:
class CourseNotificationView(ModelViewSet): queryset = CourseNotification.objects.all() serializer_class = CourseNotificationSerializer authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get_queryset(self): # IsAuthenticated权限已保证user一定存在,无需额外判断 return CourseNotification.objects.filter(user=self.request.user) def retrieve(self, request, *args, **kwargs): serializer = self.get_serializer(self.get_queryset(), many=True) return Response(data=serializer.data)
验证
修复后调用新增接口,序列化器create返回的是模型实例,DRF会自动把实例序列化为数据并封装为Response返回,不会再出现属性不存在的错误。
内容的提问来源于stack exchange,提问作者Wasim
相关产品推荐
相关产品推荐

