Django+MongoDB社交应用POST请求获取关注用户ID返回None问题
问题原因及解决方案
一、要关注用户的ID返回None的原因
你通过Postman发送的是JSON格式的POST请求(请求头为Content-Type: application/json),而request.POST仅用于解析表单编码(application/x-www-form-urlencoded)的请求数据。对于JSON请求,Django REST Framework会将请求体数据解析到request.data中,因此用request.POST.get('id')无法获取到值,自然返回None。
二、字段类型不匹配的原因
你的FollowersCount模型中,follower和user字段定义为CharField,需要传入字符串类型的值,但代码中直接传入了User模型实例(如follower=follower),Django无法将模型实例直接存入字符型字段,因此抛出类型错误。
修改后的代码示例
1. 修正views.py中的数据获取与字段赋值
# logged in user follows / unfollows user based on id class FollowView(APIView): def post(self, request): token = request.COOKIES.get('jwt') if not token: raise AuthenticationFailed('Unauthenticated!') try: payload = jwt.decode(token, 'secret', algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated!') follower = User.objects.filter(id=payload['id']).first() print(follower) # 从request.data获取JSON格式的id参数 user_id = request.data.get('id') print(user_id) response = Response() # 先验证目标用户是否存在 try: user_followed = User.objects.get(id=user_id) except User.DoesNotExist: response.data = {'message': '目标用户不存在'} return response # 用用户ID的字符串形式匹配CharField follow_record = FollowersCount.objects.filter(follower=str(follower.id), user=str(user_followed.id)).first() if follow_record: follow_record.delete() response.data = { 'message': f'{follower.username} 已取消关注 {user_followed.username}' } else: FollowersCount.objects.create(follower=str(follower.id), user=str(user_followed.id)) response.data = { 'message': f'{follower.username} 已关注 {user_followed.username}' } return response
2. 更规范的模型优化建议(可选)
建议将FollowersCount模型的字段改为ForeignKey,更符合Django ORM的设计规范,避免字符串类型匹配的问题:
class FollowersCount(models.Model): follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='followers') # 确保一个用户不能重复关注同一用户 class Meta: unique_together = ('follower', 'user')
对应views中可直接使用模型实例操作:
# 检查关注关系 if FollowersCount.objects.filter(follower=follower, user=user_followed).exists(): FollowersCount.objects.filter(follower=follower, user=user_followed).delete() # ...返回取消关注消息 else: FollowersCount.objects.create(follower=follower, user=user_followed) # ...返回关注消息
内容的提问来源于stack exchange,提问作者Sparsh Bohra
相关产品推荐
相关产品推荐

