我正在尝试更新用户的个人资料图片。用户的个人资料将在用户创建时自动创建。那时设置了默认头像。
我正在使用令牌身份验证
Authorization : Token a877b60afeb45e1ada12e10ecf4d0c8065b15569
但是在尝试更新我的
时request.data
<QueryDict: {'date_of_birth': ['1990-05-02'], 'profile_image': [<InMemoryUploadedFile: image_5854.jpg (image/jpeg)>]}>
serilizer.data
{'profile_image': None, 'date_of_birth': '1990-05-02'}
的 Models.py
@deconstructible
class UploadToPathAndRename(object):
def __init__(self, path):
self.sub_path = path
def __call__(self, instance, filename):
ext = filename.split('.')[-1]
# get filename
if instance.pk:
filename = '{}.{}'.format(instance.pk, ext)
else:
# set filename as random string
filename = '{}.{}'.format(uuid4().hex, ext)
# return the whole path to the file
return os.path.join(self.sub_path, filename)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
date_of_birth = models.DateField(null=True, blank=True)
profile_image = models.ImageField(upload_to=UploadToPathAndRename(os.path.join('images/avatar/')),
default='images/avatar/default.jpg')
participated = models.IntegerField(default=0)
won = models.IntegerField(default=0)
runner_up = models.IntegerField(default=0)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
Serializers.py
class ProfilePUTSerializer(ModelSerializer):
profile_image = ImageField(max_length=None, use_url=True)
class Meta:
model = Profile
fields = ('profile_image', 'date_of_birth',)
Views.py
class ProfilePUTAPIView(APIView):
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
def put(self, request):
print(request.data)
print(request.content_type)
print(request.stream)
serializer = ProfilePUTSerializer(data=request.data)
if serializer.is_valid():
user = Profile.objects.get(user_id=request.user.pk)
user.__dict__.update(serializer.data)
user.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
请建议做什么? 感谢