Problem : I’m unable to save the both models in database from a single serialzer.
Description : I’m using djoser auth library for registration and authentication. for that i’m using custom django auth user and mapped it with userprofile model.
Since i’m using userprofile along with the django user, i have to use custom register serializer.
# My Models
class CustomUser(AbstractUser):
username = None
email = models.EmailField(_("email address"), unique=True)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = []
objects = CustomUserManager()
class UserProfile(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name="userProfile")
user_guid = models.UUIDField(
default=uuid.uuid4,
unique=True,
editable=False
)
user_type = models.IntegerField(choices=UserType.choices(), default=UserType.BUYER)
wallet_balance = models.FloatField()
created_at = models.DateTimeField(auto_now=True)
updated_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['created_at' ] # Corrected the ordering syntax
#My Serializer
CustomUser = get_user_model()
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ['user_guid', 'user_type', 'wallet_balance', 'created_at', 'updated_at']
read_only_fields = ['user_guid', 'created_at', 'updated_at']
class CustomUserCreateSerializer(DjoserUserCreateSerializer):
userProfile = UserProfileSerializer()
class Meta:
model = CustomUser
fields = ['id', 'email', 'password', 'userProfile']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user_profile_data = validated_data.pop('userProfile')
user = CustomUser.objects.create_user(**validated_data)
UserProfile.objects.create(user=user, **user_profile_data)
return user
#settings.py
# django auth model
AUTH_USER_MODEL = 'users.CustomUser'
# djoser settings
DJOSER = {
'SERIALIZERS': {
'user_create': 'users.v1.serializers.CustomUserCreateSerializer',
'user': 'users.v1.serializers.CustomUserCreateSerializer',
'current_user': 'users.v1.serializers.CustomUserCreateSerializer',
}
}
Error : raise ValueError(
ValueError: Cannot assign “{‘user_type’: 1, ‘wallet_balance’: 0.0}”: “CustomUser.userProfile” must be a “UserProfile” instance.