Django Creating a Custom User with the Django Rest Framework

后端 未结 1 1902
陌清茗
陌清茗 2021-01-01 03:59

I\'m trying to create a custom user using the Django Rest Framework. I got it to the point to where I can create a regular user, but I\'m unsure on how to extend it to the c

相关标签:
1条回答
  • 2021-01-01 04:12

    You can do it two ways, either by creating a profile Serializer or without it. With Serializer,

    class UserProfileSerializer(serializers.ModelSerializer):
        languages = serializers.ListField(child=serializers.CharField(max_length=30, allow_blank=True))
    
        class Meta:
            model = UserProfile
            fields = ('languages',)
    
    class UserSerializer(serializers.ModelSerializer):
        password = serializers.CharField(write_only=True)
        userprofile = UserProfileSerializer(required=False)
    
        class Meta:
            model = User
            fields = ('first_name', 'last_name', 'email', 'username', 'password', 'userprofile')
    
    
        def create(self, validated_data, instance=None):
            profile_data = validated_data.pop('userprofile')
            user = User.objects.create(**validated_data)
            user.set_password(validated_data['password'])
            user.save()
            UserProfile.objects.update_or_create(user=user,**profile_data)
            return user
    

    without a profile serializer

    class UserSerializer(serializers.ModelSerializer):
        password = serializers.CharField(write_only=True)
        languages = serializers.ListField(child=serializers.CharField(max_length=30, allow_blank=True), source="userprofile.languages")
    
        class Meta:
            model = User
            fields = ('first_name', 'last_name', 'email', 'username', 'password', 'lanugages')
    
    
        def create(self, validated_data, instance=None):
            profile_data = validated_data.pop('userprofile')
            user = User.objects.create(**validated_data)
            user.set_password(validated_data['password'])
            user.save()
            UserProfile.objects.update_or_create(user=user,**profile_data)
            return user
    
    0 讨论(0)
提交回复
热议问题