这是我的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与序列化数据相关联?
答案 0 :(得分:2)
request.data为immutable,因此您应首先创建副本:
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)