Replies: 3 comments
-
I've got a similar profile in a Django project and I chose to write a class RegisterSerializer(UserSerializer):
# Profile fields
phone_number = serializers.CharField(source="profile.phone_number")
language_preferences = serializers.CharField(source="profile.language_preferences")
class Meta:
model = User
read_only_fields = ["id"]
fields = read_only_fields + [
"first_name",
"last_name",
"email",
"password",
"phone_number",
"language_preferences",
]
extra_kwargs = {
"password": {"write_only": True},
}
def create(self, validated_data):
# Hash password before saving
raw_password = validated_data["password"]
validated_data["password"] = make_password(raw_password)
# Extract profile fields from validated data
phone_number = validated_data.pop("phone_number", None)
language_preferences = validated_data.pop("language_preferences", None)
user = super().create(user_data)
# Create profile instance once the user is created
profile = UserProfile.objects.create(
user=user,
phone_number=phone_number,
language_preferences=language_preferences,
)
return user Alternatively, you could also:
|
Beta Was this translation helpful? Give feedback.
0 replies
-
I end up doing this: class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ['phone_number', 'language_preferences']
class UserSerializer(serializers.ModelSerializer):
profile = UserProfileSerializer()
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name', 'password', 'profile')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
profile_data = validated_data.pop('profile')
password = validated_data.pop('password')
user = User.objects.create(**validated_data)
user.set_password(password)
user.save()
UserProfile.objects.create(user=user, **profile_data)
return user From what I see DRF is very optionated which doesn't help when you want to implement best practices. |
Beta Was this translation helpful? Give feedback.
0 replies
-
Source Argument Documentation: https://www.django-rest-framework.org/api-guide/fields/#source |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I am building an API based application.
Users register through an API.
For registration an extended user model has been written as proposed by Django documentation:
How to write the signup view and serializer for this model?
Beta Was this translation helpful? Give feedback.
All reactions