0

I created a custom serializer that extends dj_rest_auth's RegisterSerializer, added the extra user_type field, overrode the get_cleaned_data method to include the user_type in the cleaned data then configured the custom registration serializer used for registration.

Here's my code:

class CustomRegisterSerializer(RegisterSerializer):

    user_type = serializers.ChoiceField(choices=[('seeker', 'Seeker'), ('recruiter', 'Recruiter')])

    class Meta:
        model = User
        fields = "__all__"

    def get_cleaned_data(self):
        data = super().get_cleaned_data()
        data['user_type'] = self.validated_data.get('user_type', '')
        return data
class Profile(models.Model):
    class Type(models.TextChoices):
        seeker = "Seeker"
        recruiter = "Recruiter"
    
    base_type = Type.seeker
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    user_type = models.CharField(choices=Type.choices, default=base_type, max_length=20)

    class Meta:
        verbose_name = "Profile"
        verbose_name_plural = "Profiles"

    def __str__(self):
        return self.user.username
class CustomRegisterView(RegisterView):
    serializer_class = CustomRegisterSerializer

1 Answers1

1

There's a piece missing in your code. You've added the user_type to the cleaned data but haven't shown how the Profile gets created and how the user_type is stored in the Profile model when a new user registers.

Here's how you can complete the registration process by creating the associated profile:

Override the save method in your CustomRegisterSerializer.

class CustomRegisterSerializer(RegisterSerializer):

    # ... [rest of your code]

    def save(self, request):
        user = super().save(request)
        user_type = self.validated_data.get('user_type')
        Profile.objects.create(user=user, user_type=user_type)
        return user
Mihail Andreev
  • 979
  • 4
  • 6