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.
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'
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With