背景背景
我使用django rest framework和django-rest-auth来构建API。我的身份验证方案不使用电子邮件/用户名和密码的默认身份验证,并且需要Profile
模型上的其他数据。
出于这个原因,我使用自定义注册序列化程序并覆盖设置中的REGISTER_SERIALIZER
类。
这是序列化程序如下:
class UserProfileSerializer(serializers.ModelSerializer):
phone_number = PhoneNumberField()
class Meta(object):
model = Profile
fields = ('phone_number', 'birth_date', 'anniversary', 'user_type',)
class UserRegisterSerializer(serializers.Serializer):
username = serializers.CharField(
max_length=get_username_max_length(),
min_length=allauth_settings.USERNAME_MIN_LENGTH,
required=allauth_settings.USERNAME_REQUIRED
)
email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED)
serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED)
password1 = serializers.CharField(write_only=True)
password2 = serializers.CharField(write_only=True)
profile = UserProfileSerializer()
..............
Validation methods
..............
def custom_signup(self, request, user):
pass
def get_cleaned_data(self):
return {
'username': self.validated_data.get('username', ''),
'password1': self.validated_data.get('password1', ''),
'email': self.validated_data.get('email', '')
}
def save(self, request):
adapter = get_adapter()
user = adapter.new_user(request)
self.cleaned_data = self.get_cleaned_data()
adapter.save_user(request, user, self)
self.custom_signup(request, user)
setup_user_email(request, user, [])
profile_data = self.validated_data.pop('profile', {})
user_repo.create_object(user=user, **profile_data)
return user
问题
序列化程序和相应的端点的工作原理是它正在创建用户和关联的配置文件,但在返回响应时的序列化步骤中,我收到以下错误:
KeyError: "Got KeyError when attempting to get a value for field `profile` on serializer `UserRegisterSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `OrderedDict` instance.
Original exception text was: 'profile'."
如您所见,该字段存在于序列化程序中。我尝试将字段添加到Meta
classe的字段属性中,但它没有用。
我已将其缩小到to_representation
中行号rest_framework/serializers.py
的{{1}}函数。当序列化程序尝试在嵌套的序列化程序上调用488
时,会发生错误。
谢谢!
修改:This is the view in library which uses this serializer
编辑-1 :Stack trace of the error