Viewset 'create' custom assign value in Django Rest Framework

11,447

What @Anzel said would work but if you want to do it in django-rest-framework you could override the create method of your CustomUserSerializer. Like:

class CustomUserSerializer(serializers.ModelSerializer):

    groups = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    def create(self, validated_data):
        user = CustomUser.objects.create_user(
            username    =validated_data['email'], # HERE
            email       =validated_data['email'],
            password    =validated_data['password'],
            first_name  =validated_data['first_name'], 
            last_name   =validated_data['last_name'],
            avatar      =validated_data['avatar'],
        )

        user.groups = validated_data['groups']
        return user

    class Meta:
       model = CustomUser
       fields = (
           'id', 
           'first_name', 
           'last_name', 
           'email', 
           'password', 
           'avatar', 
           'groups'
       )
Share:
11,447
Sola
Author by

Sola

My development journey --> iOS --> Django --> ionic --> Angular --> !?

Updated on July 03, 2022

Comments

  • Sola
    Sola over 1 year

    Would like to set a CustomUser's username by using the input email, but where to do the custom assigning, in view? At the same time it receiving a file as well.

    Models.py

    class CustomUser(AbstractUser):
        avatar = models.ImageField(max_length=None, upload_to='avatar', blank=True)
    

    Serializers.py

    class CustomUserSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = CustomUser
            fields = ('id', 'first_name', 'last_name', 'email', 'password', 'avatar', 'groups')
    

    Views.py

    class CustomUserViewSet(viewsets.ModelViewSet):
    
        queryset = CustomUser.objects.all()
        serializer_class = CustomUserSerializer
    

    thank you in advance.

  • Sola
    Sola about 9 years
    One question, so if I got a field "groups", how should I assign in create method? cause when i assign as "groups =validated_data['groups']", it give me an error
  • Sam R.
    Sam R. about 9 years
    @CYChong, how do you POST group? Do you include group's id in request?
  • Sola
    Sola about 9 years
    yes, i include group id in the request (the serializer I added a 'groups' field), which using the default groups by the UserModel
  • Sam R.
    Sam R. about 9 years
    @CYChong, Single group or multiple groups?
  • Sola
    Sola about 9 years
    can multi-selection (multiple-groups)