覆盖rest-auth UserDetailsS​​erializer

时间:2018-06-28 20:30:06

标签: django django-rest-auth

我正在努力覆盖UserDetailsS​​erializer。它向我显示“用户”对象没有属性“ UserProfile”。我尝试了许多方法,但更新功能似乎不正确,它阻止了该过程。

class UserProfile(serializers.ModelSerializer):

    class Meta(object):
        """Meta options."""

        model = UserModel
        fields = (
            'model_pic',
            'address',
            'city',
            'country',
        )

class UserSerializer(UserDetailsSerializer):
     ss = UserProfile(required=False)

     class Meta(UserDetailsSerializer.Meta):
        fields = UserDetailsSerializer.Meta.fields + ('ss',)

    def update(self, instance, validated_data):
        profile_data = validated_data.pop('ss')
        profile_image = profile_data.get('profile_image')
        address = profile_data.get('address')
        city = profile_data.get('city')
        country = profile_data.get('country')
        instance = super(UserSerializer, self).update(instance, validated_data)

        # get and update user profile
        profile = instance.profile_data
        if profile_data:
            if profile_image:
                profile.profile_image = profile_image
            if address:
                profile.address = address
            if city:
                profile.city = city
            if country:
                profile.country = country
            profile.save()
        return instance

model.py

class UserModel(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, default=1)
    model_pic = models.ImageField(upload_to = 'media/', default = '400.jpg')
    address = models.CharField(max_length=255, default='')
    city = models.CharField(max_length=155, default='')
    country = models.CharField(max_length=155, default='')

    def __str__(self):
        return self.user.username

0 个答案:

没有答案