Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Viewset 'create' custom assign value in Django Rest Framework

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.

like image 705
Sola Avatar asked Jan 04 '15 06:01

Sola


1 Answers

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'
       )
like image 143
Sam R. Avatar answered Sep 18 '22 17:09

Sam R.