Django休息框架AttributeError:无法在Serializer

时间:2017-05-20 16:58:33

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

背景背景

我使用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

0 个答案:

没有答案