【发布时间】:2020-10-31 22:41:48
【问题描述】:
如何使用序列化程序更新我的用户配置文件,当我更新我的用户配置文件时出现此错误:为序列化程序 accounts.serializers.AccountProfileSerializer 编写显式 .update() 方法,或在点源序列化程序字段上设置 read_only=True。
class AccountProfileSerializer(serializers.ModelSerializer):
gender = serializers.CharField(source='accountprofile.gender')
phone = serializers.CharField(source='accountprofile.phone')
location = serializers.CharField(source='accountprofile.location')
birth_date = serializers.CharField(source='accountprofile.birth_date')
biodata = serializers.CharField(source='accountprofile.biodata')
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'last_login', 'date_joined',
'gender', 'phone', 'location', 'birth_date', 'biodata')
class AccountProfileViewSet(APIView):
permission_classes = [
permissions.IsAuthenticated,
]
def get(self, request, format=None):
profile = User.objects.get(pk=self.request.user.pk)
serializer = AccountProfileSerializer(profile, many=False)
return Response(serializer.data)
def put(self, request):
profile = User.objects.get(pk=self.request.user.pk)
serializer = AccountProfileSerializer(profile, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
【问题讨论】:
-
能否请您复制粘贴错误的完整回溯?
-
AssertionError at /api/accounts/profile/
.update()方法默认不支持可写点源字段。为序列化器accounts.serializers.AccountProfileSerializer编写显式.update()方法,或在点源序列化器字段上设置read_only=True。这是完整的错误 -
在
create方法中弹出属于accountprofile的数据并将它们与不属于User模型的字段分开,然后将它们分别保存在create中。或者您可以编辑问题并在那里添加accountprofileModel,以便我可以帮助您全面实施。 -
对不起我的意思是
update方法
标签: django django-models django-rest-framework django-views django-serializer