Is there a better way to create a user with additional profile fields at the same time?

30 views
Skip to first unread message

Duke Dougal

unread,
Nov 7, 2020, 2:00:18 PM11/7/20
to Django REST framework

This works, but is the result of many hours googling and voodoo programming.

It is a serializer that creates a user and at the same time accepts an additional field (personname) that is stored in the user's connected Profile.

Although I have managed to make it work, it feels like I have hacked to make it work - a nasty solution.

For some reason I had to add the get_personname method to the class - without it I got an error saying this method was missing.

I also had to get the value for the personname field out of self.initial_data['personname'] which also seems hacky.

Is there a better, cleaner, more idiomatic way to create a user and at the same time add fields to their profile?

I'm using Django REST framework 3.11

class UserCreateSerializer(serializers.ModelSerializer):
     email = serializers.EmailField()
    personname = serializers.SerializerMethodField(method_name=None)

     def get_personname(self, value):
         return self.initial_data['personname']

     def validate_email(self, value):
         lower_email = value.lower()
         if User.objects.filter(email__iexact=lower_email).exists():
             raise serializers.ValidationError("An account exists with that email")
         return lower_email

     def validate_username(self, value):
         username_lower = value.lower()
         if User.objects.filter(username__iexact=username_lower).exists():
             raise serializers.ValidationError("That username is taken")
         return username_lower

     class Meta(dj_UserCreateSerializer.Meta):
         model = User
         fields = ('email', 'username', 'password', 'personname')

     def create(self, validated_data):
         user = User.objects.create(
         username=validated_data.get('username'),
         email=validated_data.get('email'),
         password=validated_data.get('password')
    )
     user.set_password(validated_data.get('password'))
     user.save()
     user.profile.personname=self.initial_data['personname']
     user.save()
     return user







Chetan Ganji

unread,
Nov 8, 2020, 6:50:20 AM11/8/20
to django-res...@googlegroups.com

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-rest-framework/9ecb925a-9eb4-4075-88b3-fa15046692bdn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages