Django休息框架图像上传错误

时间:2018-05-26 21:03:28

标签: python django django-rest-framework django-serializer

这是我的UserProfile模型,

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE, )
    badge = models.ImageField(upload_to='media/badges/', null=True)
    reputation = models.IntegerField(default=0)
    status = models.CharField(max_length=255, null=True, blank=True)
    thumbnail = models.ImageField(upload_to='media/user/', blank=True, null=True)

这是Serializer类,

class UserProfileSerializer(serializers.ModelSerializer):
    thumbnail = serializers.ImageField(max_length=None, use_url=True)

    class Meta:
        model = models.UserProfile
        fields = ('badge', 'reputation', 'status', 'thumbnail',)

我更新图片的API就是这样,

class CreateUpdateUserThumbnail(views.APIView):

    def post(self, request, **kwargs):
        try:
            user = User.objects.get(id=kwargs.get('user_id'))
        except User.DoesNotExist:
            return Response({"Error": "User does not exist"}, status=status.HTTP_404_NOT_FOUND)
        request.data['user_id'] = user.id
        serializer = UserProfileSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

这是我尝试使用POSTMAN上传图片时出现的错误。

return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: bouncer_userprofile.user_id

如何将user_id与序列化数据相关联?

2 个答案:

答案 0 :(得分:2)

request.dataimmutable,因此您应首先创建副本:

data = request.data.copy()
data['user_id'] = user.id
serializer = UserProfileSerializer(data=data)

答案 1 :(得分:1)

您需要在user_profile实例化

上传递UserProfileSerializer实例
serializer = UserProfileSerializer(instance=user.profile, data=request.data)

您的观点将如下所示

class CreateUpdateUserThumbnail(views.APIView):

    def post(self, request, **kwargs):
        try:
            user = User.objects.get(id=kwargs.get('user_id'))
        except User.DoesNotExist:
            return Response({"Error": "User does not exist"}, status=status.HTTP_404_NOT_FOUND)
        serializer = UserProfileSerializer(instance=user.profile, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)