用于在Django Rest Framework中创建用户配置文件的序列化器

问题描述

我正在尝试在Django Rest框架中更新用户配置文件 这样我就可以在使用信号创建用户的同时创建用户个人资料

现在我正在尝试更新创建的配置文件:-

// models.py

class User(AbstractBaseUser,PermissionsMixin):
    phone_regex=RegexValidator(regex = r'^[6-9]\d{9}$',message='please enter the correct phonenumber')

    #name_regex=RegexValidator(regex=r'/^[A-Za-z]+$/',message='Please enter the correct name')
    
    phone=models.CharField(validators=[phone_regex],max_length=15,unique=True)
    
    date_joined=models.DateTimeField(verbose_name='date joined',auto_Now_add=True)
    last_login=models.DateTimeField(verbose_name='last login',auto_Now=True)
    active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False) # a admin user; non super-user
    admin = models.BooleanField(default=False)
    first_login=models.BooleanField(default=True)

    USERNAME_FIELD='phone'
    required_FIELDS = [] 

class UserProfile(models.Model):
    # There is an inherent relationship between the Profile and
    # User models. By creating a one-to-one relationship between the two,we
    # are formalizing this relationship. Every user will have one -- and only
    # one -- related Profile model.

    GENDER = (
        ('M','Homme'),('F','Femme'),)
    user = models.OnetoOneField(
        User,related_name="profile",on_delete=models.CASCADE
    )

    # Each user profile will have a field where they can tell other users
    # something about themselves. This field will be empty when the user
    # creates their account,so we specify blank=True.
    email=models.EmailField(unique=True,validators=[validate_email],max_length=254,blank=True,null=True)
    name=models.CharField(max_length=15,blank=True)
    dateofbirth=models.DateField(auto_Now=False,null=True,blank=True)
    Gender=models.CharField(max_length=1,choices=GENDER,null=True)
    address1 = models.CharField(
        "Address",max_length=1024,null=True
    )

    address2 = models.CharField(
        "Society",null=True

    )
    address3 = models.CharField(
        "Landmark",null=True
        
    )
    zip_code = models.CharField(
        "ZIP / Postal code",max_length=12,null=True
    )

    city = models.CharField(
        "City",default ="Gurugram",null=True
    )

    country = models.CharField(
        "Country",max_length=10,default="India",null=True
    )

    # In addition to the `bio` field,each user may have a profile image or
    # avatar. This field is not required and it may be blank.

    # A timestamp representing when this object was created.
    created_at = models.DateTimeField(auto_Now_add=True,blank=True)

    # A timestamp representing when this object was last updated.
    updated_at = models.DateTimeField(auto_Now=True,blank=True)

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

@receiver(post_save,sender=User)
def create_profile_for_user(sender,instance=None,created=False,**kargs):
        if created:
            UserProfile.objects.get_or_create(user=instance)

// Serializer.py

class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields=("name",)

class UserSerializer(serializers.ModelSerializer):
    user = UserProfileSerializer(many=True)
    class Meta:
        model = User
        fields = ('user','phone',)

    def create(self,validated_data):
        user_data = validated_data.pop('user')
        user = User.objects.create(**user_data)
        profile = user_data.objects.create(user=user,**validated_data)
        return profile 
    
    def update(self,instance,validated_data):
            
            print("update function")
        
        #    profile_data = validated_data.pop('profile')
        #    print(profile_data)
            profile_data = validated_data.pop('user')
            profile = instance.profile
          #  print("profile is ",profile)

            print(profile_data.name)
            print("name in validation ",validated_data['name']," type is ",print(type(validated_data)))

            instance.username = validated_data.get('name',instance.username)
            instance.email = validated_data.get('email',instance.email)
            instance.save()
            print("name is ",instance.profile.name )
            #profile.Gender = validated_data['Gender'],#profile.email = validated_data['email'],#profile.dateofbirth=validated_data['dateofbirth'],#profile.address1=validated_data['address1'],##profile.address2=validated_data['address2'],#profile.address3=validated_data['address3']
          #  print("1",profile)
            #print(profile.Gender)
            #print(profile.email)
            #print(profile.dateofbirth)
            profile.save()
            print("2",profile)
            print(profile.name)
            print("save done")

            return instance

// views.py

class ProfileCreateAPIView(CreateAPIView):
   
    def put(self,request,*args,**kwargs):
        print("my print 0",request)
        header_token = request.Meta.get('HTTP_AUTHORIZATION',None)
        print(header_token)
        access_token=header_token.split(' ')[1]
        status,user =validate_token(access_token)
        print(request.data)
        
        
        user_profile_serializer = UserProfileSerializer(
                    instance=user,data=request.data
        )
        user_serializer = UserSerializer(
                instance=user,data=request.data)
        print("my print 1",user_profile_serializer.is_valid())
        print("my print 2",user_serializer.is_valid())
        if user_profile_serializer.is_valid() and user_serializer.is_valid():
            user_profile_serializer.save()
            print("user_profile save done")
            user_serializer.save()
            print("user save done")

            return Response(
                    status=rt_status.HTTP_200_OK)
        # Combine errors from both serializers.
      #  errors = dict()
       # errors.update(user_profile_serializer.errors)
        #errors.update(user_serializer.errors)
        else:
            return Response(status=rt_status.HTTP_400_BAD_REQUEST)
        '''
        return Response(status=rt_status.HTTP_400_BAD_REQUEST)
        '''

现在的问题是,当我按下api时,我从UserProfile中将user_serializer.is_valid()设为TRUE,但设为False。 我觉得获取个人资料数据存在一些问题。 但是我不明白如何解决该问题。 非常感谢您的帮助。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)